source:
doc/papers/concurrency/examples/PingPong.c
@
331eacbe
Last change on this file since 331eacbe was a573c22, checked in by , 5 years ago | |
---|---|
|
|
File size: 1.6 KB |
Line | |
---|---|
1 | #include <stdio.h> |
2 | |
3 | typedef struct PingPong { |
4 | int restart; // style 1 |
5 | int N, i; |
6 | const char * name; |
7 | struct PingPong * partner; |
8 | void * next; // style 2 |
9 | } PingPong; |
10 | #define PPCtor( name, N ) { 0, N, 0, name, NULL, NULL } |
11 | |
12 | void comain( PingPong * pp ) __attribute__(( noinline )); |
13 | void comain( PingPong * pp ) { |
14 | #if 0 |
15 | if ( __builtin_expect(pp->next != 0, 1) ) goto *pp->next; |
16 | pp->next = &&cycle; |
17 | for ( ; pp->i < pp->N; pp->i += 1 ) { |
18 | #ifdef PRINT |
19 | printf( "%s %d\n", pp->name, pp->i ); |
20 | #endif // PRINT |
21 | asm( "mov %0,%%rdi" : "=m" (pp->partner) ); |
22 | asm( "mov %rdi,%rax" ); |
23 | #ifndef OPT |
24 | #ifdef PRINT |
25 | asm( "add $16, %rsp" ); |
26 | #endif // PRINT |
27 | asm( "popq %rbp" ); |
28 | #endif // ! OPT |
29 | |
30 | #ifdef OPT |
31 | #ifdef PRINT |
32 | asm( "popq %rbx" ); |
33 | #endif // PRINT |
34 | #endif // OPT |
35 | asm( "jmp comain" ); |
36 | cycle: ; |
37 | } // for |
38 | #endif // 0 |
39 | |
40 | #if 1 |
41 | static void * states[] = {&&s0, &&s1}; |
42 | goto *states[pp->restart]; |
43 | s0: pp->restart = 1; |
44 | for ( ; pp->i < pp->N; pp->i += 1 ) { |
45 | #ifdef PRINT |
46 | printf( "%s %d\n", pp->name, pp->i ); |
47 | #endif // PRINT |
48 | asm( "mov %0,%%rdi" : "=m" (pp->partner) ); |
49 | asm( "mov %rdi,%rax" ); |
50 | #ifndef OPT |
51 | #ifdef PRINT |
52 | asm( "add $16, %rsp" ); |
53 | #endif // PRINT |
54 | asm( "popq %rbp" ); |
55 | #endif // ! OPT |
56 | |
57 | #ifdef OPT |
58 | #ifdef PRINT |
59 | asm( "popq %rbx" ); |
60 | #endif // PRINT |
61 | #endif // OPT |
62 | asm( "jmp comain" ); |
63 | s1: ; |
64 | } // for |
65 | #endif // 0 |
66 | } |
67 | |
68 | int main() { |
69 | enum { N = |
70 | #ifdef PRINT |
71 | 5 |
72 | #else |
73 | 1000000000 |
74 | #endif // PRINT |
75 | }; |
76 | PingPong ping = PPCtor( "ping", N ), pong = PPCtor( "pong", N ); |
77 | ping.partner = &pong; pong.partner = &ping; |
78 | comain( &ping ); |
79 | } |
80 | |
81 | // Local Variables: // |
82 | // tab-width: 4 // |
83 | // compile-command: "gcc-9 -g -DPRINT PingPong.c" // |
84 | // End: // |
Note: See TracBrowser
for help on using the repository browser.