【问题标题】:vector as input to pthread_create向量作为 pthread_create 的输入
【发布时间】:2019-07-04 21:14:17
【问题描述】:

我将一个结构传递给 pthread_create。该结构的一个组成部分是矢量数据。每个线程中的循环中的“数据”push_back。当循环的大小很小时,代码可以正确运行。当循环很大时。我收到以下错误消息:

munmap_chunk(): 无效指针 munmap_chunk(): 无效指针 中止(核心转储)

我试过 m

// 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(): 无效指针 中止(核心转储)

【问题讨论】:

    标签: c++ vector pthreads


    【解决方案1】:

    在本例的特定情况下(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)

    【讨论】:

    • 哇。解决了这个问题。您能否更具体地说明为什么使用 std::thread 而不是 pthread?有什么例子吗?谢谢!
    • 您已经在使用现代 C++ 和 std::thread::hardware_concurrency() 那么为什么不保持一致呢?而且它在现代 C++ 标准中非常便携。
    • 抱歉新手问题。是不是像用 std::thread 替换 pthread 一样简单?
    • @David 刚刚在答案中添加了指向文档的链接(带有一些示例)。
    • @David 你可能会发现std::future 是一个有趣的选择。 It describes an asynchronous operation a bit better than a thread.
    猜你喜欢
    • 1970-01-01
    • 2016-02-09
    • 2021-10-07
    • 2019-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-08
    相关资源
    最近更新 更多