gpt4 book ai didi

linux - 为什么新创建的线程不是通过pthread_create()返回参数获取它的tid,而是pthread_self()

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

这是《Unix环境高级编程》中创建线程的示例代码。关于线程的创建,err = pthread_create(&ntid, NULL, thr_fn, NULL); 新创建的线程是否可以只使用ntid打印自己的threadID,而不是调用pthread_self()?

#include "apue.h"
#include <pthread.h>

pthread_t ntid;

void
printids(const char *s)
{
pid_t pid;
pthread_t tid;

pid = getpid();
tid = pthread_self();
printf("%s pid %u tid %u (0x%x)\n", s, (unsigned int)pid,
(unsigned int)tid, (unsigned int)tid);
}

void *
thr_fn(void *arg)
{
printids("new thread: "); /* for the newly created thread,can it
* print its own threadID just using ntid,
* instead of calling pthread_self()
*/
return((void *)0);
}

int
main(void)
{
int err;

err = pthread_create(&ntid, NULL, thr_fn, NULL);
if (err != 0)
err_quit("can't create thread: %s\n", strerror(err));
printids("main thread:");
sleep(1);
exit(0);
}

最佳答案

让我们检查规范:

http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_create.html

pthread_create(pthread_t *restrict thread,

Upon successful completion, pthread_create() shall store the ID of the created thread in the location referenced by thread.

The calling thread can obtain the ID of the created thread through the return value of the pthread_create() function, and the newly created thread can obtain its ID by a call to pthread_self().

问题是:ntid是调用函数的变量;即使它是全局的,从线程读取这个全局变量也不会扩展到两个或更多创建的线程。

另一个问题是执行的时间和顺序。 pthread_create 将线程 id 写入 ntid after 创建新线程:

Upon successful completion, pthread_create() shall store the ID of the created thread in the location referenced by thread.

因此,在没有同步的情况下从创建的线程读取 ntid 是不安全的,新线程可能会在将实际值写入全局之前读取。

所以,你应该使用pthread_self:http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_self.html

The pthread_self() function shall return the thread ID of the calling thread.

The pthread_self() function provides a capability similar to the getpid() function for processes and the rationale is the same: the creation call does not provide the thread ID to the created thread.

关于linux - 为什么新创建的线程不是通过pthread_create()返回参数获取它的tid,而是pthread_self(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38136384/

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