source: tests/concurrency/channels/hot_potato.cfa @ 314c9d8

Last change on this file since 314c9d8 was 50be8af, checked in by Peter A. Buhr <pabuhr@…>, 14 months ago

clean up command-line handling and I/O

  • Property mode set to 100644
File size: 1.8 KB
Line 
1#include <locks.hfa>
2#include <fstream.hfa>
3#include <stdio.h>
4#include <channel.hfa>
5#include <thread.hfa>
6#include <time.hfa>
7#include <string.h>
8
9size_t total_operations = 0;
10ssize_t Processors = 1, Tasks = 4;                                              // must be signed
11
12owner_lock o;
13
14typedef channel( int ) Channel;
15
16Channel * chain;
17
18bool done = false;
19int id_counter = 0;
20thread Task { int id; int right; };
21static inline void ?{}( Task & this ) with(this) {
22    id = __atomic_fetch_add( &id_counter, 1, __ATOMIC_SEQ_CST );
23    right = (id + 1) % Tasks;
24}
25void main(Task & this) with(this) {
26    size_t runs = 0;
27    try {
28        for ( ;; ) {
29            if ( done ) break;
30            remove( chain[id] );
31            insert( chain[right], 0 );
32            runs++;
33        }
34    } catch ( channel_closed * e ) {}
35    lock( o );
36    total_operations += runs;
37    unlock( o );
38}
39
40int main( int argc, char * argv[] ) {
41    switch ( argc ) {
42          case 3:
43                if ( strcmp( argv[2], "d" ) != 0 ) {                    // default ?
44                        Tasks = ato( argv[2] );
45            if ( Tasks < 1 ) fallthru default;
46                } // if
47          case 2:
48                if ( strcmp( argv[1], "d" ) != 0 ) {                    // default ?
49                        Processors = ato( argv[1] );
50                        if ( Processors < 1 ) fallthru default;
51                } // if
52          case 1:                                                                                       // use defaults
53                break;
54          default:
55                exit | "Usage: " | argv[0]
56             | " [ processors (> 0) | 'd' (default " | Processors
57                         | ") ] [ channel size (>= 0) | 'd' (default " | Tasks
58                         | ") ]" ;
59        } // switch
60
61    processor proc[Processors - 1];
62
63    sout | "start";
64
65    chain = aalloc( Tasks );
66    for ( i; Tasks ) {
67        chain[i]{ 1 };
68    }
69
70    insert( chain[0], 0 );
71    {
72        Task t[Tasks];
73        sleep(10`s);
74        done = true;
75        for ( j; Tasks )
76            close( chain[j] );
77    }
78   
79    // sout | total_operations;
80
81    sout | "done";
82
83    adelete(chain);
84
85    return 0;
86}
Note: See TracBrowser for help on using the repository browser.