Created
October 22, 2016 20:13
-
-
Save dryman/328056c694d3384d034d60d6855633af 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 <stdlib.h> | |
#include <stdio.h> | |
#include <pthread.h> | |
#include <stdatomic.h> | |
#include <stdbool.h> | |
static atomic_bool lock = false; | |
static volatile int counter = 0; | |
void* thread_start(void *arg) | |
{ | |
for (int i = 0; i < 10000; i++) | |
{ | |
bool expected_bool = false; | |
while (!atomic_compare_exchange_weak_explicit( | |
&lock, &expected_bool, true, | |
memory_order_acquire, | |
memory_order_relaxed)) | |
{ | |
expected_bool = false; | |
} | |
counter++; | |
atomic_store_explicit(&lock, false, memory_order_release); | |
} | |
return NULL; | |
} | |
int main() | |
{ | |
pthread_t p1, p2; | |
pthread_create(&p1, NULL, thread_start, NULL); | |
pthread_create(&p2, NULL, thread_start, NULL); | |
pthread_join(p1, NULL); | |
pthread_join(p2, NULL); | |
printf("counter: %d\n", counter); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment