Atomics demo
This commit is contained in:
parent
e1bd06eb69
commit
8661c89633
1 changed files with 43 additions and 0 deletions
43
atomics.c
Normal file
43
atomics.c
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
#include <stdatomic.h>
|
||||
#include <stdio.h>
|
||||
#include <threads.h>
|
||||
|
||||
atomic_int x; // _Atomic int
|
||||
|
||||
int thread1(void *arg) {
|
||||
(void)arg;
|
||||
|
||||
printf("Thread 1: Sleeping for 1.5 seconds\n");
|
||||
thrd_sleep(&(struct timespec){.tv_sec = 1, .tv_nsec = 500000000}, NULL);
|
||||
|
||||
printf("Thread 1: Setting x to 3490\n");
|
||||
x = 3490;
|
||||
|
||||
printf("Thread 1: Exiting\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
int thread2(void *arg) {
|
||||
(void)arg;
|
||||
|
||||
printf("Thread 2: Waiting for 3490\n");
|
||||
while (x != 3490); // spin here
|
||||
|
||||
printf("Thread 2: Got 3490--exiting!\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
x = 0;
|
||||
|
||||
thrd_t t1, t2;
|
||||
|
||||
thrd_create(&t1, thread1, NULL);
|
||||
thrd_create(&t2, thread2, NULL);
|
||||
|
||||
thrd_join(t1, NULL);
|
||||
thrd_join(t2, NULL);
|
||||
|
||||
printf("Main : Threads are done, so x better be 3490\n");
|
||||
printf("Main : And indeed, x == %d\n", x);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue