Search code examples
cmultithreadingpthreadsposix

Why is pthread_equal threadsafe?


If I look at the implementation of pthread_equal it looks as follows:

int
__pthread_equal (pthread_t thread1, pthread_t thread2)
{
  return thread1 == thread2;
}
weak_alias (__pthread_equal, pthread_equal)

with

typedef unsigned long int pthread_t;

Posix documentation says pthread_equal is threadsafe. But the call to pthread_equals copies and therefore accesses the thread1 and thread2 variables. If those variables are global and changed in this moment by another thread this would lead to undefined behavior.

So should pthread_t not be an atomic? Or does it behave atomically which is ensured in some other way?


Solution

  • This implementation of pthread_equal (which is going to be specific to the POSIX implementation it goes with) does not access any variables except local ones. In C, arguments are always passed by value. thread1 and thread2 are local variables in the function who take their values from the expressions the caller uses when making the call.

    With that said, even if they weren't, there would be no problem of thread-unsafety here. Rather, if the caller accessed pthread_t objects that could be changed concurrently by other threads without using appropriate synchronization mechanisms to preclude that, it's a data race bug in the caller, not a thread-safety matter in the callee.