使用C++11标准多线程库,首先创建若干个线程,传入线程要执行的函数,参数放在后面传入。
join函数使得这些线程同时执行,主线程等待,detach函数会使得线程与主线程分离,一起并行
在线程函数中使用全局变量,由于多核CPU的机制,数据会出现错误,需要加锁处理,频繁的加锁会增加时间消耗。
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
mutex m;
const int tCount = 4;
int sum = 0;
void workFun(int index)
{
for (int i = 0; i < 100000; i++) {
m.lock(); // 加锁
sum++;
m.unlock();
}
}
int main()
{
thread t[tCount];
for (int n = 0; n < tCount; n++)
t[n] = thread(workFun, n);
for (int n = 0; n < tCount; n++) {
t[n].join();
//t[n].detach();
}
cout << sum << endl;
for (int n = 0; n < 4; n++)
cout << "Hello,main thread." << endl;
return 0;
}