注意新建线程时 thread proc1(proc11, ref(a)); 1.这里需要写ref(a) 2.这里的线程名称和函数名称需要设置不一样的
#include<iostream>
#include<thread>
#include<mutex>
using namespace std;
mutex m;
void proc11(int& a)
{
m.lock();
cout << "proc1函数正在改写a" << endl;
cout << "原始a为" << a << endl;
a=a+2;
cout << "现在a为" << a << endl;
m.unlock();
}
void proc22(int& a)
{
m.lock();
cout << "proc2函数正在改写a" << endl;
cout << "原始a为" << a << endl;
a=a+1;
cout << "现在a为" << a << endl;
m.unlock();
}
int main()
{
int a = 0;
thread proc1(proc11, ref(a));
thread proc2(proc22, ref(a));
proc1.join();
proc2.join();
cout << "最终a为" << a << endl;
return 0;
}
|