source: tests/concurrency/channels/hot_potato.cfa @ 55b060d

Last change on this file since 55b060d was c26bea2a, checked in by Peter A. Buhr <pabuhr@…>, 19 months ago

first attempt at renaming directory tests/concurrent to tests/concurrency to harmonize with other concurrency directory names

  • 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;
10size_t Processors = 1, Tasks = 4;
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
40
41int main( int argc, char * argv[] ) {
42    switch ( argc ) {
43          case 3:
44                if ( strcmp( argv[2], "d" ) != 0 ) {                    // default ?
45                        Tasks = atoi( argv[2] );
46            if ( Tasks < 1 ) goto Usage;
47                } // if
48          case 2:
49                if ( strcmp( argv[1], "d" ) != 0 ) {                    // default ?
50                        Processors = atoi( argv[1] );
51                        if ( Processors < 1 ) goto Usage;
52                } // if
53          case 1:                                                                                       // use defaults
54                break;
55          default:
56          Usage:
57                sout | "Usage: " | argv[0]
58             | " [ processors (> 0) | 'd' (default " | Processors
59                         | ") ] [ channel size (>= 0) | 'd' (default " | Tasks
60                         | ") ]" ;
61                exit( EXIT_FAILURE );
62        } // switch
63    processor proc[Processors - 1];
64
65    sout | "start";
66
67    chain = aalloc( Tasks );
68    for ( i; Tasks ) {
69        chain[i]{ 1 };
70    }
71
72    insert( chain[0], 0 );
73    {
74        Task t[Tasks];
75        sleep(10`s);
76        done = true;
77        for ( j; Tasks )
78            close( chain[j] );
79    }
80   
81    // sout | total_operations;
82
83    sout | "done";
84
85    adelete(chain);
86
87    return 0;
88}
Note: See TracBrowser for help on using the repository browser.