gpt4 book ai didi

c - 当使用特定数量的线程时,Pthread 不起作用

转载 作者:行者123 更新时间:2023-11-30 15:40:44 28 4
gpt4 key购买 nike

我遇到了一个奇怪的现象:我的 C 程序在某些特定数量的线程下无法工作,例如8.

当我用“fprintf”调试时,我发现问题出现在pthreads的创建上:

298 /* work for each thread */
299 void* work(void *t)
300 {
301 long tid;
302 tid = (long)t;
303 fprintf(stderr, "In thread %lu\n", tid);
304
...
368 pthread_exit((void*)t);
369 }

513 /* main function */
514 int my_main(struct Params params)
515 {
...
pthread_t* threads;
threads = malloc(threads_num * sizeof(pthread_t));
574 long t;
575 int rc;
576 for (t=0; t<threads_num; t++)
577 {
578 fprintf(stderr, "create %lu\n", t);
579 rc = pthread_create(&threads[t], NULL, work, (void*)t);
580 if(rc)
581 {
582 printf("ERROR: return code from pthread_creat() is %d\n", rc);
583 exit(-1);
584 }
585 }
...
599 for(t=0; t<threads_num; t++)
600 pthread_join(threads[t], NULL);
...
615 return 0;
616 }

结果如下:

create 0
create 1
create 2
create 3
create 4
create 5
In thread 0
In thread 3
In thread 4
create 6
In thread 1
In thread 2
In thread 5
create 7
In thread 6
Segmentation fault

线程 7 可能会出现哪些潜在问题?有什么想法吗?

其他可能有用的信息是:代码在我的 MacBook Pro 上运行良好,并使用 GCC 作为编译器。这里的问题是我在一些 Linux 服务器(openSUSE)上使用 GCC 编译它们的情况。

最佳答案

感谢您的所有回答和评论!

我找到了这个奇怪的段错误的根源。

在代码的其他部分,我将 float 加载到一些数组中。但是我错误地使用了malloc(sizeof(int) * length)。此前,我使用float类型,由于floatint具有相同的大小,这个bug没有出现在我早期版本的代码中。不过最近我又更新了类型从 floatdouble,这导致了这种奇怪的行为。

抱歉,放置了与错误来源无关的代码。没想到这个bug会导致pthread的奇怪行为。

关于c - 当使用特定数量的线程时,Pthread 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20860809/

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