c++ - vector 作为 pthread_create 的输入

标签 c++ vector pthreads

我将一个结构传递给 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/

相关文章:

android - 使用 OpenCV4Android (java API) 保存 ORB 特征向量

c++排序不使用自定义函数

c++ - 如何创建类对象的 vector vector

c - 以非常低的优先级运行线程

c++ - 为什么一个函数接受一个空指针?

c++ - 用 FFmpeg 编写多线程视频和音频数据包

c++ - 在 typedef 结构体上使用 sizeof 运算符

c - 是否可以在启动时根据用户输入设置全局变量或定义?

c++ - __cplusplus 指令在各种编译器中是如何定义的?

c++ - 构造函数中的字段初始化破坏内存