概述
atomic:原子性
读-改-写 不可分割
线程安全
用来解决该篇中的问题全局变量跨线程修改的问题-CSDN博客
代码
cpp
#include<stdatomic.h>
#include<stdio.h>
#include<pthread.h>
atomic_int global=99;
void* thread_func(void* arg){
printf("[child thread]before:%d\n",atomic_load(&global));
atomic_store(&global,22);
int i;
for(i=0;i<10000;i++){
printf("[child thread] %d time global: %d\n",i,atomic_load(&global));
}
pthread_exit(NULL);
}
int main(){
pthread_t tid;
if(pthread_create(&tid,NULL,thread_func,NULL)!=0){
perror("Thread Create Fail!");
return 1;
}
int i;
for(i=0;i<10000;i++){
printf("[main thread] %d time global: %d\n",i,atomic_load(&global));
if(atomic_load(&global)==22){
pthread_cancel(tid);
break;
}
}
printf("child finished global: %d\n",atomic_load(&global));
return 0;
}
编译链接
cc main.c -lpthread

输入./a.out回车运行程序
第一次运行


第二次运行


第三次运行
