Skip to content

Instantly share code, notes, and snippets.

@vsrinivas
Created February 25, 2023 22:57
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 vsrinivas/8816b68fa807964c8ec3957cc6ba22b8 to your computer and use it in GitHub Desktop.
Save vsrinivas/8816b68fa807964c8ec3957cc6ba22b8 to your computer and use it in GitHub Desktop.
#include <pthread.h>
static int go;
static int should_exit;
void *ctr(void *p) {
int *counter = p;
for (;;) {
if (__atomic_load_n(&go, __ATOMIC_RELAXED))
break;
}
for (;;) {
if (__atomic_load_n(&should_exit, __ATOMIC_RELAXED))
break;
*counter = *counter + 1;
}
}
int main(int argc, char *argv[]) {
int i, n;
int *counters;
pthread_t *threads;
i = atoi(argv[1]);
counters = calloc(sizeof(int), i);
threads = calloc(sizeof(pthread_t), i);
for (n = 0; n < i; n++) {
pthread_create(&threads[n], NULL, ctr, &counters[n]);
}
__atomic_store_n(&go, 1, __ATOMIC_RELAXED);
sleep(1);
__atomic_store_n(&should_exit, 1, __ATOMIC_RELAXED);
for (n = 0; n < i; n++) {
pthread_join(threads[n], NULL);
}
for (n = 0; n < i; n++) {
printf("%d: %d\n", n, counters[n]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment