gpt4 book ai didi

C pthread_t 读/写允许吗?

转载 作者:太空宇宙 更新时间:2023-11-04 00:57:44 28 4
gpt4 key购买 nike

假设我有代码片段:

...
pthread_t tt;
...
pthread_create(&tt, NULL, thread_func, NULL);
...

if( tt != 0)
{
pthread_join(tt, NULL);
tt = 0;
}

问题:tt可读吗?可写?当我四处搜索时,没有发现这方面的明确规范,而且 pthread_t 是不透明的。谢谢和问候,

最佳答案

pthread_t当然是可读可写的。问题是您不知道向它写入什么(或如何写入)或如何从中读取。您可以将整个事物作为不透明单元传递或获取其地址,或将其传递给多个 pthread_xxx 函数,但除此之外,pthread_t 值是不透明且未指定的,因此您无法可移植地为其赋值或对其当前值做出任何决定。

例如,在 Linux 中,tt = 0; 赋值是安全的,但在不同的实现中可能并非如此。即使安全,也不能保证零值是合法的“无效”值,您可以使用它来表示线程不存在。

pthread_self(3) 的 linux 手册页包括以下文本:

POSIX.1 allows an implementation wide freedom in choosing the type used to represent a thread ID; for example, representation using either an arithmetic type or a structure is permitted. Therefore, variables of type pthread_t can't portably be compared using the C equality operator (==); use pthread_equal(3) instead.

Thread identifiers should be considered opaque: any attempt to use a thread ID other than in pthreads calls is nonportable and can lead to unspecified results.

因此唯一可移植的方法是为每个 pthread_t 保留一个单独的标志,以表明它是否(或仍然)存在。

关于C pthread_t 读/写允许吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53163420/

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