【问题标题】:Bus error on OSX - pthreadsOSX 上的总线错误 - pthreads
【发布时间】:2023-03-18 07:50:02
【问题描述】:

我正在努力解决以下问题:

有一个小程序正在尝试移植到调用函数 doWork() 的 OSX(intel) 通过 pthread_create,在函数中,我首先创建一个 long 数组,如下所示:

长 myarray [尺寸]

在 OSX 上,对于以下 DIMENSION 值,我得到以下信息:

0->65434 = 很好 65435->67037 = 信号总线 67037+ = SIGSEGV

我在这里完全感到困惑,我知道 SIGBUS 通常是由于内存对齐问题,我检查了 sizeof(long) 并且在这个平台上它似乎是 8。有人可以指出我应该在这里阅读的文档的正确方向吗?

这里是来源:

#include pthread.h #include stdio.h #define NUM_THREADS 5 #define DIMENSION 12345 void *doStuff(void *threadid) { long array[DIMENSION]; pthread_exit(NULL); } int main (int argc, char *argv[]) { pthread_t threads[NUM_THREADS]; int rc; long t; for(t=0; t lt NUM_THREADS; t++){ printf("In main: creating thread %ld\n", t); rc = pthread_create(&threads[t], NULL, doStuff, (void *)t); if (rc){ printf("ERROR; return code from pthread_create() is %d\n", rc); exit(-1); } } pthread_exit(NULL); }

【问题讨论】:

    标签: c macos pthreads


    【解决方案1】:

    看起来你正在溢出堆栈。

    当您调用 pthread_create 时,您需要将 long 数组转换为 malloced 数组,或者使用 pthread_attr_setstacksize 和朋友创建一个更大的堆栈。

    默认线程堆栈大小在平台之前有很大差异,这可以解释为什么代码可以在其他平台上运行。

    https://computing.llnl.gov/tutorials/pthreads/#Stack 有一些示例代码。

    至于为什么会得到 sigbus,可能是因为创建数组的行为是用垃圾覆盖了 pthreads 内部数据结构的某些部分,导致 pthreads 尝试清理线程时出现对齐错误。

    【讨论】:

    • 谢谢,这是有道理的,使用 getstacksize() 我被告知线程有 524288 个字节的堆栈,假设 long 是 8 个字节,8*62435 就在那个(523480)之下,我想其余的都是某种开销?
    • 听起来很可能。线程底部会有一个 pthread 块,调用堆栈上的任何函数都会产生少量开销。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-28
    • 2014-05-19
    相关资源
    最近更新 更多