简体   繁体   中英

C pthread_t read/write permissible?

Assume I have the code snippet:

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

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

Question: is tt readable? writable? As I googled around, found no clear spec in this regard, and pthread_t is opaque. Thanks & regards,

The pthread_t is certainly readable and writable. The problem is that you don't know what (or how) to write to it or how to read from it. You can pass the entire thing around as an opaque unit or take its address, or pass it to several pthread_xxx functions, but otherwise, the pthread_t value is opaque and unspecified so you can't portably assign a value to it or make any determination about its current value.

In linux, for example, the tt = 0; assignment is safe, but it might not be so on a different implementation. And even if safe, there is no guarantee that a value of zero is a legitimate "invalid" value that you can use to signal absence of a thread.

The linux man page for pthread_self(3) includes this text:

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.

So the only portable way to do this is to keep a separate flag in conjunction with each pthread_t to signal whether it is (or is still) in existence.

您只需要关心pthread_create的返回值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM