Does POSIX require comparison operators for `pthread_key_t`, `pthread_once_t` and `pthread_t`?

Viewed 36

The standards document for sys/types.h (https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_types.h.html), says "There are no defined comparison or assignment operators for the following types:", then lists a bunch of types. However, some of the non-arithmetic (or rather not-necessarily arithmetic) types are missing from that list. Notably, pthread_key_t, pthread_once_t and pthread_t are missing. It seems odd to say "these types don't have assignment and comparison operators" when that's already implied for non-arithmetic types. Does this mean that conforming implementations must provide comparison and assignment operators for those 3 types?

1 Answers

TL;DR: Comparison or assignment of pthread_key_t and such may or may not be valid, depending on the particular pthreads implementation. Comparison or assignment of pthread_mutex_t and such must never be valid.

No, it doesn't mean that conforming implementations have to provide comparison or assignment operators for those types. In fact, if the implementation defines one of those types as a struct, a comparison operator would be impossible to provide. POSIX builds on C not C++, and C doesn't allow comparison operations on structs.

However, conforming implementations aren't required to use structs. If they chose to, they are free to use arithmetic types for example. If they did use an arithmetic type to define one of pthread_key_t, pthread_once_t or pthread_t, then comparison and assignment operations on that type would likely be valid. (However, an application shouldn't rely on them if it wants to be portable).

This is not the case with pthread_mutex_t for example. The standard doesn't specify how pthread_mutex_t should be defined, so an implementation could theoretically use an arithmetic type to define pthread_mutex_t. However, the standard is saying here that comparison and assignment operations between instances of pthread_mutex_t must be forbidden.

Presumably the reasoning for this is similar to why the C++ standard goes out of it's way to forbid copying instances of std::mutex. Copying a mutex is a nonsensical operation. The same is true for most/all of the other types the standard forbids comparison or assignment of.

Related