最近在学习多线程,写代码的时候出现了问题,不是很理解,希望大家指导一下
代码示例如下:
#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
#include <windows.h>
using namespace std;
int g_num = 0;
mutex g_mutex;
void ThreadFun(int a)
{
cout << "Create Thread "<< a << endl;
for (size_t i = 0;i<10000000;i++)
{
lock_guard <mutex> member(g_mutex);
g_num++;
}
}
int main()
{
vector <thread*> vecThread;
for (size_t k = 0; k < 8; k++)
{
thread* th =new thread(ThreadFun, j);
vecThread.push_back(th);
th->join(); //加入join()就会出现问题
}
for (auto begin = vecThread.begin(); begin != vecThread.end();++begin)
{
(*begin)->join();
// Sleep(100);
cout << "g_num = " << g_num << endl;
return 0;
}
}[]()
```c++
上面想将线程一依次放入容器内,为什么就不行了呢?
出现如下问题:
0x7746A6F2 处(位于 TreadStudy.exe 中)有未经处理的异常: Microsoft C++ 异常: std::system_error,位于内存位置