Created
May 8, 2017 18:18
-
-
Save antirez/b01d38db02a0bac3b2b4328411449c37 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 <stdint.h> | |
#include <pthread.h> | |
#include <stdio.h> | |
volatile uint64_t x = 0; | |
void *writeThread(void *arg) { | |
for (uint64_t i = 0; i < 10000000; i++) { | |
while(!__sync_bool_compare_and_swap(&x,x,i+(i<<32))); // x = i+(i<<32) | |
} | |
return NULL; | |
} | |
void *readThread(void *arg) { | |
while(1) { | |
uint64_t aux = __sync_sub_and_fetch(&x,0); // aux = x | |
if ((aux >> 32) != (aux & UINT32_MAX)) { | |
printf("Wrong\n"); | |
} | |
} | |
} | |
int main(void) { | |
pthread_t t1, t2; | |
pthread_create(&t1,NULL,writeThread,NULL); | |
pthread_create(&t2,NULL,readThread,NULL); | |
pthread_join(t1,NULL); | |
printf("%llu\n", (unsigned long long)x); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment