gpt4 book ai didi

c - 仅使用一个 pthread_t 变量和使用多个 pthread_t 变量有什么区别?

转载 作者:行者123 更新时间:2023-11-30 15:19:12 25 4
gpt4 key购买 nike

我想知道使用不同数量的 pthread_t 变量的差异。
这是我编写的一个简单代码:

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

void *thread(void *vargp);

int main(int argc, char **argv)
{
pthread_t tid;

for (int i = 0; i < 5; i++){
int* a = malloc(sizeof(int));
*a = i;
pthread_create(&tid, NULL, thread, a);
}

if(pthread_join(tid, NULL) == -1){
printf("error");
exit(1);
}
}

void *thread(void *vargp)
{
int count = 1;
for(int i = 0; i <3; i++){
printf("count : %d, value : %d\n", count, (*(int *)vargp));
count++;
}
}

它按照我的意思工作得很好。然而,我觉得奇怪的是,它创建了 5 个线程,但只使用一个 pthread_t 变量!...我看到一些示例,其中使用与它将创建的线程数相同数量的 pthread 变量。例如,如果我要创建如下所示的 5 个线程,则必须创建 5 个长度的 pthread_t 数组,例如 pthread_t tid[5] 。你能告诉我有什么区别吗?谢谢

最佳答案

传递给 pthread_create

pthread_t 变量是一个线程标识符,可以根据需要重用。因此,使用相同的标识符 tid 创建多个线程的方式没有任何问题。但是,除了使用它创建的最后一个线程之外,您将丢失所有其他线程的标识,因为 tid 在循环中不断被覆盖。

但是,如果您想从线程接收退出值(使用 pthread_join)或执行一些其他操作,例如分离线程(使用 pthread_detach) - - 您可以创建一个处于分离状态的线程,或者线程本身可以将其分离),从您的主线程设置/获取调度参数(使用pthread_setschedparampthread_getschedparam)等不能这样做,因为您没有线程的 ID。

简而言之,代码非常好,如果您想操作 < 中的线程,则需要存储 ID(例如在示例中使用数组 tid[5]) em>外部(与线程内部相反——线程可以使用pthread_self()获取其ID)。

关于c - 仅使用一个 pthread_t 变量和使用多个 pthread_t 变量有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30819452/

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