===== 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 __Analyze the code and tell which results can be output.__ \\ Remember that global variables are by default zero-initialized. 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 volatile char data[64 * 3]; volatile char *const a = data + 64; volatile char *const b = data + 64 * 2; atomic_char vA, vB, control; void *th1(void *arg) { control++; while (control != 2); *b = 1; vA = *a; return NULL; } void *th2(void *arg) { control++; while (control != 2); volatile int dummy = 44; while (dummy--); *a = 1; vB = *b; return NULL; } int main() { pthread_t t1, t2; pthread_create(&t1, NULL, th1, NULL); pthread_create(&t2, NULL, th2, NULL); pthread_join(t1, NULL); pthread_join(t2, NULL); printf("%d %d\n", vA, vB); return 0; }
~~META: language = en ~~