用atomic解决全局变量跨线程修改的问题

概述

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回车运行程序

第一次运行

第二次运行

第三次运行

相关推荐
SuperByteMaster2 小时前
callee和caller的区别
c语言
kkeeper~11 小时前
0基础C语言积跬步之数据在内存中的存储
c语言·数据结构·算法
qq38624619613 小时前
更新补发第6天:7天学会C语言,每天5分钟,不需要基础
c语言·for循环·循环语句·while循环·do-while循环
张暮笛19 小时前
深入浅出:C语言中的“虚表分派”
c语言
社交怪人20 小时前
【等差数列】信息学奥赛一本通C语言解法(题号1035)
c语言
不会C语言的男孩20 小时前
VS Code 中搭建 C/C++ 开发环境(MSYS2 编译器)
c语言·c++
学困昇21 小时前
Linux 信号机制详解:从 Ctrl+C 到 SIGCHLD,一文理解进程信号
linux·c语言·开发语言·人工智能·面试
AI科技星21 小时前
维度原本——基于超复数谱系的全域维度统一理论
c语言·前端·javascript·网络·electron
SoftLipaRZC1 天前
C语言字符完全指南:字符函数与字符串函数
c语言·开发语言·算法