当前位置: 首页 > news >正文

(c++)线程的创建、互斥锁的使用、线程数组

 1.创建10个线程,每个线程都做10万次全局变量num1++操作,然后输出这个全局变量,预想结果应该是100万。但是线程可能在cpu分配的一个时间片中做不完10万次+1的操作,这时候cpu会被其他线程抢占,由于num1++不是一个原子操作(操作过程中可能会发生中断),导致++其实没有做完,所以num1的最终结果会小于100万。

2.创建10个线程,每个线程都做10万次全局变量num2++操作,与前者不同的是,这次对num2++操作加入互斥锁,也就是让num2++成为一个“原子操作”(操作过程不会被中断),所以结果符合预期为100万

#include<iostream>
#include<thread>//使用thread包含这个库
#include<mutex>//使用互斥锁包含这个库using namespace std;//不加这个的话每个标识符前都要添加 std:: 才能用mutex mtx2;//用来给num2++的操作加互斥锁//两个全局变量用于做累加操作
int num1 = 0;
int num2 = 0;void increase1()//让全局变量num1累加100000次
{for (int i = 0; i < 100000; i++){num1++;}
}
void increase2()//让全局变量num2累加100000次
{for (int i = 0; i < 100000; i++){mtx2.lock();num2++;mtx2.unlock();}
}int main()
{//创建10个进程并调用函数increase1,每个进程让全局变量num1++100000次thread t1(increase1);thread t2(increase1);thread t3(increase1);thread t4(increase1);thread t5(increase1);thread t6(increase1);thread t7(increase1);thread t8(increase1);thread t9(increase1);thread t10(increase1);//等待这10个线程执行完,不然下方的输出会提前输出num1=。。。t1.join();t2.join();t3.join();t4.join();t5.join(); t6.join();t7.join(); t8.join();t9.join();t10.join();cout << "预期结果小于100万,未加锁num1=" << num1 << endl;/*预期结果小于100万,因为num1++不是原子操作,线程运行到一半会被其他线程抢占cpu导致++没做完*///创建10个进程并调用函数increase2,每个进程让全局变量num2++100000次thread t11(increase2);thread t12(increase2);thread t13(increase2);thread t14(increase2);thread t15(increase2);thread t16(increase2);thread t17(increase2);thread t18(increase2);thread t19(increase2);thread t20(increase2);//等待这10个线程执行完,不然下方的输出会提前输出num2=。。。t11.join();t12.join();t13.join();t14.join();t15.join();t16.join();t17.join();t18.join();t19.join();t20.join();cout << "预期结果100万,加锁num2=" << num2 << endl;//预期结果100万,由于加了锁,num2++不会被中断system("pause");return 0;
}

运行结果

 创建线程也可以用线程数组

#include<iostream>
#include<thread>
using namespace std;
int n = 0;void increase() //n累加1000万次
{for (int i = 0; i < 10000000; i++){n++;}}int main()
{//创建一个有10个元素的线程数组thread my_thread[10];//启动10个线程,让每个线程调用increase函数for (int i = 0; i < 10; i++){my_thread[i]=thread(increase);}//等待这10个线程执行完for (int i = 0; i < 10; i++){my_thread[i].join();}//结果会小于1亿cout << "全局变量n=" << n << endl;system("pause");return 0;
}

运行结果(每次都可能不一样)

 

同样的,也可以给n++加互斥锁,这样预期结果就会是1亿


http://www.mrgr.cn/news/31268.html

相关文章:

  • 网络编程练习:UDP聊天室
  • 虚拟机安装nginx需要注意的一些事项
  • Linux 进程3
  • 5G技术对IT行业的影响及未来发展
  • 操作系统 | 学习笔记 | | 王道 | 5.2 设备独立软件
  • OpenAi assistant run always fails when called from PHP
  • 基于嵌入式的智能物流柜( 触摸屏/0.96寸oled屏)
  • pytorch快速入门(一)—— 基本工具及平台介绍
  • Bigemap GIS Office 2024注册机 全能版地图下载软件
  • nginx常用配置及调优
  • 力扣题解(统计特殊整数)
  • 使用adb命令进行内存测试
  • Jenkins自动化部署后端项目看这篇就够了
  • 万魔头戴式耳机怎么样?万魔、西圣、JBL三款旗舰机型激战评测!
  • Vue 修饰符 | 指令 区别
  • 【秋招笔试】09.20-58同城秋招(已改编)-三语言题解
  • Python基础
  • Python教你用20行代码做一个骰子模拟博弈游戏
  • Rocprofiler测试
  • Redis-01 入门和十大数据类型