-
-
Save 38/fdc0dc200d3da142458c420a2e37459d to your computer and use it in GitHub Desktop.
乱序执行实验
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 <pthread.h> | |
#include <stdio.h> | |
int x, y; | |
int r1, r2; | |
volatile int chance, complete; | |
typedef struct { | |
int mask; | |
volatile int *x, *y, *r; | |
} param_t; | |
void* thread_main(void* ar) | |
{ | |
param_t* p = (param_t*)ar; | |
volatile int* x = p->x; | |
volatile int* y = p->y; | |
int r, mask = p->mask; | |
for(;;) | |
{ | |
int obs; | |
do { | |
obs = chance; | |
} while((obs & mask) == 0 || !__sync_bool_compare_and_swap(&chance, obs, obs ^ mask)); | |
asm volatile ("" : : : "memory"); | |
*x = 1; | |
//__sync_synchronize(); | |
asm volatile ("" : : : "memory"); | |
r = *y; | |
asm volatile ("" : : : "memory"); | |
*p->r = r; | |
do { | |
obs = complete; | |
} while(!__sync_bool_compare_and_swap(&complete, obs, obs + 1)); | |
} | |
return NULL; | |
} | |
int main() | |
{ | |
param_t p1 = { | |
.x = &x, | |
.y = &y, | |
.r = &r1, | |
.mask = 0x1 | |
}; | |
param_t p2 = { | |
.x = &y, | |
.y = &x, | |
.r = &r2, | |
.mask = 0x2 | |
}; | |
pthread_mutex_init(&m, NULL); | |
pthread_t t1, t2; | |
pthread_create(&t1, NULL, thread_main, &p1); | |
pthread_create(&t2, NULL, thread_main, &p2); | |
int count[4] = {}; | |
int i; | |
for(i = 0; i < 10000000; i ++) | |
{ | |
x = y = 0; | |
r1 = r2 = 0; | |
while(!__sync_bool_compare_and_swap(&chance, 0, 0x3)); | |
while(complete != 2); | |
complete = 0; | |
count[r1 * 2 + r2] ++; | |
} | |
for(i = 0; i < 4; i ++) | |
printf("r1 = %d r2 = %d count = %d\n", i / 2, i % 2, count[i]); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment