多线程中,每个线程都拥有自己的栈空间,但是对于全局变量、静态变量以及堆上空间,是共享于多个线程间的,这可以有效的在多个线程间共享数据,但也是多线程竞争的主要来源:
#include <iostream>
#include <thread>
using namespace std;
int g_d{0};
void tFunc(int a)
{
for(int i = 0; i < a; ++i)
{
g_d++;
}
cout<<"thread:"<<a<<" g_d="<<g_d<<endl;
}
int main(){
thread t1(tFunc, 60000);
thread t2(tFunc, 80000);
t1.join();
t2.join();
return 0;
}
两个线程分别对全局变量g_d进行操作,产生竞争
运行程序输出:
thread:60000 g_d=80419
thread:80000 g_d=98365
由于产生了线程竞争,因此此结果为随机的
即使通过原子类型,也无法保证程序的运行结果:
#include <iostream>
#include <atomic>
#include <thread>
using namespace std;
atomic_int g_d{0};
void tFunc(int a)
{
for(int i = 0