Why cannot I directly compare 2 thread ids instead of using pthread_equal?

无人久伴 提交于 2021-02-19 06:03:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!