Skip to content

Instantly share code, notes, and snippets.

@antirez
Created May 8, 2017 18:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antirez/b01d38db02a0bac3b2b4328411449c37 to your computer and use it in GitHub Desktop.
Save antirez/b01d38db02a0bac3b2b4328411449c37 to your computer and use it in GitHub Desktop.
#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