gpt4 book ai didi

c - 查找C程序中的错误

转载 作者:行者123 更新时间:2023-11-30 18:18:33 27 4
gpt4 key购买 nike

我有下面的 C 程序代码。其中应该存在一个仅有时会出现的幽灵错误,但是每当我运行它时,它都工作正常。我找不到错误所在

#include <pthread.h>
#include <stdio.h>
#include <string.h>

struct thread_data {
char name[255];
unsigned int num_iterations;
unsigned int some_answer;
};

void* thread_entrypoint(void *arg)
{
int i;
struct thread_data *tdata = (struct thread_data*)arg;

tdata->some_answer = 0;
for (i=0; i<tdata->num_iterations; i++) {
tdata->some_answer += i;
}

printf("Name: %s, Answer: %u\n", tdata->name, tdata->some_answer);
pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
pthread_t tid;
struct thread_data tdata;

strcpy(tdata.name, "Spartacus");
tdata.num_iterations = 100;

pthread_create(&tid, NULL, thread_entrypoint, &tdata);
pthread_detach(pthread_self());
pthread_exit(NULL);
}

最佳答案

问题是您将线程指针从主线程传递给局部变量,然后通过退出主线程或从函数返回来离开作用域:

struct thread_data tdata;

您必须在堆上分配此结构才能使其可靠地工作。这基本上取决于退出主线程是否比完成子线程更快。它可能取决于 CPU 数量、当前进程负载等,因此它是非常随机的。

关于c - 查找C程序中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35071386/

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