===== 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, barrier;
void *th1(void *arg) {
barrier++;
while (barrier != 2);
*b = 1;
vA = *a;
return NULL;
}
void *th2(void *arg) {
barrier++;
while (barrier != 2);
*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;
}
g++ -g -O0 sb.cpp -o sb
#include
#include
#include
volatile char data[64 * 3];
volatile char &a = data[64];
volatile char &b = data[64*2];
std::atomic barrier;
char th1() {
char vA;
barrier++;
while (barrier != 2);
b = 1;
vA = a;
return vA;
}
char th2() {
char vB;
barrier++;
while (barrier != 2);
a = 1;
vB = b;
return vB;
}
int main() {
auto a1 = std::async(th1);
auto a2 = std::async(th2);
char vA = a1.get();
char vB = a2.get();
printf("%d %d\n", vA, vB);
return 0;
}