gpt4 book ai didi

c - OSX 上的总线错误 - pthreads

转载 作者:行者123 更新时间:2023-12-02 08:58:09 27 4
gpt4 key购买 nike

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

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

long myarray[DIMENSION]

在 OSX 上,对于以下 DIMENSION 值,我得到以下结果:

0->65434 = fine65435->67037 = SIGBUS67037+ = 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);
}

最佳答案

看起来你正在溢出堆栈。

您需要将长数组转换为 malloced 数组,或者在调用 pthread_create 时使用 pthread_attr_setstacksize 和 friend 创建更大的堆栈。

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

示例代码:

   pthread_attr_t attr;
size_t stacksize;

pthread_attr_init(&attr);
pthread_attr_getstacksize(&attr, &stacksize);
printf("Default stack size = %li\n", stacksize);
stacksize = <....>;
printf("Amount of stack needed per thread = %li\n",stacksize);
pthread_attr_setstacksize(&attr, stacksize);
rc = pthread_create(&thread, &attr, dowork, (void *)t);

(代码最初来自 https://github.com/LLNL/HPC-Tutorials/blob/main/posix/stack_management.md )

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

关于c - OSX 上的总线错误 - pthreads,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3329379/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com