【问题标题】:C++ segmentation fault when creating pthreads创建 pthread 时出现 C++ 分段错误
【发布时间】:2015-03-15 22:56:08
【问题描述】:
void createThreads(int k){
struct threadData threadData[k];

int numThreads = k;
int i = 0;
int err = 0;

pthread_t *threads = static_cast<pthread_t*>(malloc(sizeof(pthread_t) * numThreads));
for(i = 0;i<numThreads;i++){

    threadData[i].thread_id = i;
    threadData[i].startIndex = ((N/k)*i);
    threadData[i].stopIndex = ((N/k)*(i+1));

    err = pthread_create(&threads[i], NULL, foo, (void *)&threadData[i]);


    if(err != 0){
        printf("error creating thread\n");
    }
}
}

这里,N 和 k 是整数,其中 N/k 的余数保证为 0。 包括 createThreads(numThreads);在 main 中会导致我的程序出现段错误并且将其注释掉会解决这个问题,但是我放入 createThreads 的任何 printf 调试语句(即使在函数内的第一行)都不会显示,所以我对如何调试感到很困惑这。感谢所有帮助。

【问题讨论】:

  • 这不是你问题的原因,但你为什么在 C++ 中使用 malloc?
  • struct threadData threadData[k]; 这不是合法的 C++。您不能使用变量作为条目数来创建数组。

标签: c++ segmentation-fault pthreads


【解决方案1】:

我想问题是你的 arg 参数在你的 createThreads 函数的堆栈上:

struct threadData threadData[k];

所以一旦你的线程被创建并运行,并且 createThreads 返回,threadData 就不再有效,所以你的线程函数不应该接触参数数据。否则它的未定义行为和崩溃。

所以要修复它,您应该将 threadData 设为全局(在 createThreads 之外),或者对其进行 malloc。

【讨论】:

  • 这绝对是个问题。但foo 本身也可能存在更多问题。
猜你喜欢
  • 2014-12-16
  • 2018-10-03
  • 2015-01-08
  • 1970-01-01
  • 2011-10-26
  • 2015-06-06
  • 1970-01-01
  • 2011-11-24
  • 1970-01-01
相关资源
最近更新 更多