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

第一次运行

第二次运行

第三次运行

相关推荐
冻柠檬飞冰走茶16 分钟前
PTA基础编程题目集 7-17 爬动的蠕虫(C语言实现)
c语言·开发语言·数据结构·算法
麻瓜老宋13 小时前
AI开发C语言应用按步走,表达式计算器calc的第二十二步,分号赋值链式修复、TOKEN_ASSIGN
c语言·开发语言·atomcode
SilentSlot17 小时前
【C/C++】手写 DPDK 协议栈(十一):基于 PPS、SYN 比例和源 IP 熵的 DDoS 检测
c语言·c++·tcp/ip
冻柠檬飞冰走茶19 小时前
PTA基础编程题目集 7-15 计算圆周率(C语言实现)
c语言·开发语言·数据结构·算法
Rabitebla21 小时前
C++ 内存管理全面复习:从内存分布到 operator new/delete
java·c语言·开发语言·c++·算法·leetcode
SilentSlot1 天前
【C/C++】手写 DPDK 协议栈(八):用五元组 Hash 加速连接定位
c语言·c++·哈希算法
Tisfy1 天前
LeetCode 3517.最小回文排列 I:排序(Python两行版) / 计数(O(n)时间+O(C)空间+字符串原地修改)
c语言·python·leetcode·字符串·排序·计数排序·回文
菜鸟的升级路1 天前
C语言栈刷题:LeetCode 20 有效的括号完整解题笔记
c语言·笔记·leetcode
冻柠檬飞冰走茶1 天前
PTA基础编程题目集 7-13 日K蜡烛图(C语言实现)
c语言·开发语言·数据结构·算法
SilentSlot1 天前
【C/C++】手写 DPDK 协议栈(十二):TCP 并发与自实现 epoll 的就绪事件分发
c语言·c++·tcp/ip