Created
March 17, 2019 14:31
-
-
Save YangKeao/c06a1e7e86201c3736a60e572bc58b80 to your computer and use it in GitHub Desktop.
简单地触发因为reorder而产生的问题
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <semaphore.h> | |
#include <random> | |
sem_t begin_sem1; | |
sem_t begin_sem2; | |
sem_t end_sem; | |
int X, Y; | |
int r1, r2; | |
void *ThreadFunc1(void *param) { | |
for (;;) { | |
sem_wait(&begin_sem1); | |
X = 1; | |
asm volatile("" ::: "memory"); | |
r1 = Y; | |
sem_post(&end_sem); | |
} | |
return NULL; | |
} | |
void *ThreadFunc2(void *param) { | |
for (;;) { | |
sem_wait(&begin_sem2); | |
Y = 1; | |
asm volatile("" ::: "memory"); | |
r2 = X; | |
sem_post(&end_sem); | |
} | |
return NULL; | |
} | |
int main(int argc, char *argv[]) { | |
sem_init(&begin_sem1, 0, 0); | |
sem_init(&begin_sem2, 0, 0); | |
sem_init(&end_sem, 0, 0); | |
pthread_t thread[2]; | |
pthread_create(&thread[0], NULL, ThreadFunc1, NULL); | |
pthread_create(&thread[1], NULL, ThreadFunc2, NULL); | |
int detected = 0; | |
for (int i = 1; ; ++i) { | |
X = 0; | |
Y = 0; | |
sem_post(&begin_sem1); | |
sem_post(&begin_sem2); | |
sem_wait(&end_sem); | |
sem_wait(&end_sem); | |
if (r1 == 0 && r2 == 0) { | |
detected++; | |
printf("%d %d\n", detected, i); | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment