gpt4 book ai didi

c - 多线程:简单程序段错误(核心转储)

转载 作者:太空宇宙 更新时间:2023-11-04 12:09:38 25 4
gpt4 key购买 nike

我正在尝试创建一个程序来计算从 1 到 1000 的素数。我相信代码在创建或加入 pthreads 时遇到了问题。我不断收到核心转储错误。我主要关心的是在我加入 pthread 的第二个 for 循环中。这是检查线程是否已结束的正确方法吗?

我在终端中使用 gcc --std=c99 -Wall -Werror -pthread primes.c -o primes。

    while (test_val <= FINAL){
//loop to check if thread is finished
for(int i = 0; i < THREADS; i++){
if(tid[i] == 0){
pthread_create(&tid[i], NULL, testprime, NULL);

}
}
//wait for thread to end
for(int i = 0; i < THREADS; i++){
pthread_join(tid[i], NULL);

这是错误:段错误(核心转储)

最佳答案

这里:

for(int l = 0; ti < MAX_THREADS; ti++){
if(tid[l] == 0){
pthread_create(&tid[l], NULL, testprime, NULL);
tid[l] = 1;
}
}

pthread_create 的第一个参数是输出线程句柄。在下一行,您将此值设置为 1(可能将其标记为已使用)。

当对这些无效句柄执行 pthread_join 时,您会调用未定义的行为

删除此分配,线程句柄不为 0,因此您的代码无论如何都可以工作。

关于c - 多线程:简单程序段错误(核心转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49412304/

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