===== Yet another reason that makes concurrent programming harder. ===== Below, there is a piece of code that can be compiled by issuing: gcc -g -O0 sb.c -o sb The program forks and uses shared memory, so concurrency is involved. \\ __Analyze the code and tell which results can be output.__ \\ Remember that newly allocated anonymous shared memory is always zeroed. Run the program multiple times with the following command, and observe the results: ( for((i=0;i<10000;++i)); do ./sb; done ) | sort | uniq -c Finally, explain the results.
#include #include #include #include struct data { atomic_char vA, vB, control[3]; volatile char data[64*3]; }; int main(){ struct data * const s = mmap(NULL, sizeof(struct data), PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0); atomic_char * const control = s->control; volatile char * const a = s->data + 64; volatile char * const b = s->data + 64*2; volatile char dummy = s->vA + s->vB + *a + *b; if(!fork()){ control[0]++; while(control[0]!=2); *b = 1; //while(--dummy); s->vA = *a; control[1]=1; return 0; } else { control[0]++; while(control[0]!=2); *a = 1; s->vB = *b; while(control[1]!=1); printf("%d %d\n",s->vA, s->vB); return 0; } }
~~META: language = en ~~