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

第一次运行

第二次运行

第三次运行

相关推荐
李永奉2 小时前
C语言-指针函数与函数指针及回调函数的使用
c语言·开发语言
杨丰玮4182 小时前
C语言基础知识(一)————各类符号的含义与输入输出库(stdio)
c语言·开发语言
水饺编程3 小时前
第1章,了解乌班图环境,使用浏览器和邮箱
c语言·汇编·ubuntu
Escalating_xu5 小时前
【C 语言】操作符详解(下):逗号、下标、结构体、类型转换与表达式求值
c语言
晓蛋7 小时前
C语言条件编译精讲
c语言·条件编译·宏定义·代码移植·预处理程序
ggaofeng7 小时前
Ctrl+C结束进程是如何实现的
服务器·c语言·网络
水饺编程8 小时前
第1章:开发环境搭建,在 Windows 中安装 QEMU
c语言·汇编
沐晓时光9 小时前
C语言入门,深入理解指针(1)
c语言·开发语言
天l志9 小时前
DL/T 645—2007《多功能电能表通信协议》的跨平台 C 语言实现
c语言·电表·dlt645
老王爱玩车12 小时前
工具函数——清空输入缓冲区
c语言·开发语言·学习