gpt4 book ai didi

c - 创建线程时,有些线程的线程 ID 为 0

转载 作者:太空宇宙 更新时间:2023-11-04 08:50:26 26 4
gpt4 key购买 nike

我有一个服务器应用程序,它为每个传入请求创建新线程。

但是,每隔一段时间,它会创建一个线程 ID = 0 的线程(使用 pthread_equal 来检查这一点)。我有一个结构,其中包含我传递给 pthread_create 中指定的函数的线程 ID,并在那里检查它。

为什么会创建 ID = 0 的线程?如果发生这种情况,我能做些什么吗?我不能使用这个线程,想立即退出。

============================================= ======================

typedef struct 
{
pthread_t tid;
other_struct_t Other;
} data_ptr_t;

void * worker(void * arg)
{
data_ptr_t local_data;
data_ptr_t * incoming_data = (data_ptr_t *) arg;
if (NULL == incoming_data || NULL == incoming_data->Other)
{
printf("invalid input\n");
}
else if (pthread_equal(incoming_data->tid, 0))
{
printf("invalid thread id\n");
}
else
{
// add to global thread pool
// do other stuff here
// remove from global thread pool
}
}

int main()
{
// server socket stuff
while (1)
{
// if incoming connection is valid
data_ptr_t data;
int error = pthread_create(&(data.tid), NULL, (void * (*) (void *)) worker, (void *) &data);
if (0 != errror)
{
printf("could not create thread (%d)\n", error);
}
else
{
pthread_detach(data.tid);
printf("thread dispatched\n");
}
}
}

注意:如果我创建的线程数低于 50 个左右,它就可以正常工作。超过 70,大多数线程运行良好,其余线程最终打印“无效线程 ID”。

注意:这是在 Linux 上。

最佳答案

你不能这样做:

while (1)
{
// if incoming connection is valid
data_ptr_t data;
int error = pthread_create(&(data.tid),
NULL, (void * (*) (void *)) worker, (void *) &data);

您的data_ptr_t 是堆栈上的局部变量。在 while 循环的下一次迭代中,该变量被销毁/消失/无效。

while 循环可能会在新的 worker 线程开始运行并使用您传递给它的数据之前很久就开始另一次迭代。相反,动态分配您传递给工作线程的数据,这样您就可以确保它仍然有效。

关于c - 创建线程时,有些线程的线程 ID 为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19865732/

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