矢量作为pthread_create的输入

vector as input to pthread_create

本文关键字:create 输入 pthread      更新时间:2023-10-16

我将一个结构传递给pthread_create。该结构的一个组成部分是矢量数据。"数据"在每个线程中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)