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亿



![[Spring]Spring MVC 请求和响应及用到的注解](https://i-blog.csdnimg.cn/direct/a13a99e0108c413b80c0236565120887.png)














