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

第一次运行

第二次运行

第三次运行

相关推荐
山登绝顶我为峰 3(^v^)33 小时前
C/C++ 交叉编译方法
java·c语言·c++
LONGZETECH6 小时前
新能源汽车动力电池检测仿真教学系统:C/S 分层架构与数字化实训落地全解析
大数据·c语言·开发语言·人工智能·架构·系统架构·汽车
legendary_1638 小时前
SINK芯片:Type-C统一供电时代的小家电核心方案
c语言·开发语言·人工智能·智能手机
_Doubletful8 小时前
妙用位运算:解构汉明距离至100%(提供分析与多解)
c语言·算法·leetcode
shx_wei9 小时前
从函数调用到进程替换:使用 execl、CMake 与 PowerShell 构建一个多可执行程序
linux·c语言·windows·c
李小小钦11 小时前
D. Storming Arasaka(Codeforces 2238)
c语言·开发语言·数据结构·c++·算法
gugucoding1 天前
21. 【C语言】打包不同类型:结构体
c语言·开发语言
gugucoding1 天前
31. 【C语言】堆栈与队列的实现
c语言·开发语言·数据结构·链表
Yang_jie_031 天前
笔记:数据结构(C语言版)第一章知识点详细归纳
c语言·数据结构·算法
czhaii1 天前
串口1中断收发-C语言-MODBUS协议
c语言·开发语言