Created
August 20, 2019 06:56
-
-
Save hide/0975b056482f694ed98595c139724657 to your computer and use it in GitHub Desktop.
Atomic sample (gcc -std=gnu11 -pthread -o atomic atomic.c)
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 <stdio.h> | |
#include <string.h> | |
#include <stdatomic.h> | |
#include <pthread.h> | |
#include <stdint.h> | |
#define __STDC_FORMAT_MACROS | |
#include <inttypes.h> | |
struct object | |
{ | |
_Atomic uint64_t aval; | |
uint64_t val; | |
} obj; | |
void * | |
cnt_add (void *arg) | |
{ | |
int i; | |
for (i = 0; i < 10000; i++) | |
{ | |
obj.aval++; | |
obj.val++; | |
} | |
pthread_exit (NULL); | |
} | |
int | |
main (int argc, char **argv) | |
{ | |
int i; | |
pthread_t tid[1000]; | |
memset (&obj, 0, sizeof (struct object)); | |
for (i = 0; i < 1000; i++) | |
pthread_create (&tid[i], NULL, cnt_add, NULL); | |
for (i = 0; i < 1000; i++) | |
pthread_join (tid[i], NULL); | |
printf ("obj.aval = %" PRIu64 "\n", obj.aval); | |
printf ("obj.val = %" PRIu64 "\n", obj.val); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment