我将一个结构传递给 pthread_create。该结构的一个组成部分是 vector 数据。每个线程循环中的“数据”push_back。当循环的大小很小时,代码可以正确运行。当环路很大时。我收到以下错误消息:
munmap_chunk(): 无效指针 munmap_chunk(): 无效指针 中止(核心转储)
我试过 m<100,它有效。当尝试 m<1000 时,它显示错误。
// compile using: g++ parallel_2.C -o oo -lpthread
#include <iostream>
#include <cstdlib>
#include <vector>
#include <thread>
using namespace std;
const unsigned NUM_THREADS = std::thread::hardware_concurrency();
//
struct INPUT
{
int start;
int end;
vector<int> data;
};
//
void *Loop(void *param)
{
INPUT *in = (INPUT*)param;
int start = in->start;
int end = in->end;
cout<<" start: "<<start<<" end: "<<end<<endl;
//for(int m=0; m<100000000; m++)
for(int i = start;i < end;i++)
for(int m=0; m<1000; m++) {
in->data.push_back(i);
}
//pthread_exit(NULL);
}
//
int main ()
{
pthread_t threads[NUM_THREADS];
INPUT input[NUM_THREADS];
for( int i=0; i < NUM_THREADS; i++ ){
cout << "main() : creating thread, " << i << endl;
input[i].start = i*5;
input[i].end = input[i].start + 5;
int rc = pthread_create(&threads[i], NULL,
Loop, (void *)&input[i]);
if (rc){
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
}
for(int i = 0; i<NUM_THREADS; i++)
cout<<"!! size of "<<i<<": "<<input[0].data.size()<<endl;
pthread_exit(NULL);
}
munmap_chunk(): 无效指针 munmap_chunk(): 无效指针 中止(核心转储)
最佳答案
在此示例的特定情况下(main()
假定线程已完成并查询修改后的结构),您必须在之前join()
一个线程访问它正在修改的结构。
for(int i = 0; i<NUM_THREADS; i++)
{
pthread_join(threads[i], NULL);
cout<<"!! size of "<<i<<": "<<input[0].data.size()<<endl;
}
这样,您就可以确定它已经完成,并且不再修改结构。
问题并没有出现在很少的迭代中,因为线程可能(但不确定)在 main()
中的最后一个循环试图访问它们的结构之前结束了它们的任务。
顺便说一句,你应该考虑使用std::thread
。
( https://en.cppreference.com/w/cpp/thread/thread/thread )
关于c++ - vector 作为 pthread_create 的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56894264/