Skip to content

Instantly share code, notes, and snippets.

@dryman
Created October 22, 2016 20:13
Show Gist options
  • Save dryman/328056c694d3384d034d60d6855633af to your computer and use it in GitHub Desktop.
Save dryman/328056c694d3384d034d60d6855633af to your computer and use it in GitHub Desktop.
#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