/*类型atomic_flag范例*/
#ifdef __STDC_NO_ATOMICS__
#error "Implementation does not support atomic types."
#endif
#ifdef __STDC_NO_THREADS__
#error "Implementation does not support multi-threads."
#endif
#include <stdatomic.h>
#include <stdio.h>
#include <stdlib.h>
#include <threads.h>
#define THREADS 10
atomic_flag lock = ATOMIC_FLAG_INIT;
int number = 0;
/*新线程中执行的函数。*/
int func(void *arg)
{
for(int i=0; i<10000; ++i)
{
/*获取lock。*/
while(atomic_flag_test_and_set(&lock))
;
++number;
/*释放lock。*/
atomic_flag_clear(&lock);
}
thrd_exit(0);
}
int main(void)
{
thrd_t threadId[THREADS];
for(int i=0; i<THREADS; ++i)
{
if(thrd_create(&threadId[i], func, NULL) != thrd_success)
{
perror("thrd_create error");
exit(EXIT_FAILURE);
}
}
for(int i=0; i<THREADS; ++i)
thrd_join(threadId[i], NULL);
printf("number: %d\n", number);
return 0;
}
|