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

第一次运行

第二次运行

第三次运行

相关推荐
LDR0062 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
Luminous.2 天前
C语言--day30
c语言·开发语言
玖玥拾2 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
謓泽2 天前
C语言不是语法,是通往机器的地图。
c语言·开发语言
不会C语言的男孩2 天前
Linux 系统编程 · 第 8 章:进程基础
linux·c语言
2601_951643882 天前
C语言长文整理,关键字和数据类型
c语言·数据类型·关键字·嵌入式开发·格式化输出
m0_547486662 天前
《C#语言程序设计与实践》 全套PPT课件
c语言·c#·c语言程序设计
✎ ﹏梦醒͜ღ҉繁华落℘2 天前
编程基础 --高内聚,低耦合
c语言·单片机
QK_002 天前
C语言 static 关键字三大作用
c语言·开发语言
隔窗听雨眠2 天前
C语言函数递归从入门到精通(下):性能优化与工程实践
c语言·算法·性能优化