Created
February 25, 2023 22:57
-
-
Save vsrinivas/8816b68fa807964c8ec3957cc6ba22b8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 <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