问题
I know there is a system call pthread_equal in Linux for comparing 2 thread ids. But why cannot one directly compare 2 thread ids using '==' operator?
回答1:
From the pthread_equal man page on Linux:
The pthread_equal() function is necessary because thread IDs should be considered opaque: there is no portable way for applications to directly compare two pthread_t values.
It might be a struct. It might be a pointer. It might be a pointer to a struct held somewhere. ==
might, or might not, return true for all cases it should return true and vice versa.
So you are provided with an accessor that is guaranteed to return the correct result, no matter the implementation.
回答2:
I have checked the definition of pthread_t with the gcc compiler which I am using, there it is defined as "typedef unsigned long int pthread_t;". But the definition of pthread_t is implementation dependent. While porting the same code to different platforms(hardware), if we compare directly the pthread id's it will be a problem because different platforms may implement pthread_t in different ways(implementaion dependent, like structure, or type other that unsigned long int). So to make our code portable across different platforms we are using pthread_t as an opaque type.
来源:https://stackoverflow.com/questions/37675763/why-cannot-i-directly-compare-2-thread-ids-instead-of-using-pthread-equal