pthread_t tid;
pthread_create(&tid, NULL, thr_loop, NULL);
如果我除了传递 NULL 之外传递一些值会发生什么?
最佳答案
嗯,根据manpage最后一个参数是用户定义的参数,它被传递给新线程调用的函数。
static void *
thread_start(void *arg)
{
struct thread_info *tinfo = arg;
char *uargv, *p;
printf("Thread %d: top of stack near %p; argv_string=%s\n",
tinfo->thread_num, &p, tinfo->argv_string);
uargv = strdup(tinfo->argv_string);
if (uargv == NULL)
handle_error("strdup");
for (p = uargv; *p != '\0'; p++)
*p = toupper(*p);
return uargv;
}
然后他们调用 pthread_create
如下
pthread_create(&tinfo[tnum].thread_id, &attr,&thread_start, &tinfo[tnum]);
正如你所看到的,有一个参数传递给函数,然后传递给函数
到 thread_start
函数。你可以在这里传递你喜欢的一切。
更新:
我刚刚看到,您可能还提到了其他一些 NULL
值。所以让我也解释一下:
PTHREAD_CREATE_DETACHED
- 如果调用线程不想等待已创建线程的终止,您应该使用此状态创建它。PTHREAD_CREATE_JOINABLE
- 假定您正在以某种方式等待线程,例如pthread_join
为了进一步阅读,我可以推荐 this网页。
关于c - 可附加线程和可分离线程的主要区别是什么。是否与 CPU 开销有关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32110248/