Why is a pthread mutex considered “slower” than a futex?

Futexes were created to improve the performance of pthread mutexes. NPTL uses futexes, LinuxThreads predated futexes, which I think is where the “slower” consideration comes. NPTL mutexes may have some additional overhead, but it shouldn’t be much. Edit: The actual overhead basically consists on: selecting the correct algorithm for the mutex type (normal, recursive, adaptive, … Read more

Is there an invalid pthread_t id?

Your assumption is incorrect to start with. pthread_t objects are opaque. You cannot compare pthread_t types directly in C. You should use pthread_equal instead. Another consideration is that if pthread_create fails, the contents of your pthread_t will be undefined. It may not be set to your invalid value any more. My preference is to keep … Read more

How do you query a pthread to see if it is still running?

It sounds like you have two questions here: How can I wait until my thread completes? Answer: This is directly supported by pthreads — make your thread-to-be-stopped JOINABLE (when it is first started), and use pthread_join() to block your current thread until the thread-to-be-stopped is no longer running. How can I tell if my thread … Read more

How to set the name of a thread in Linux pthreads?

As of glibc v2.12, you can use pthread_setname_np and pthread_getname_np to set/get the thread name. These interfaces are available on a few other POSIX systems (BSD, QNX, Mac) in various slightly different forms. Setting the name will be something like this: #include <pthread.h> // or maybe <pthread_np.h> for some OSes // Linux int pthread_setname_np(pthread_t thread, … Read more

Detached vs. Joinable POSIX threads

Create a detached thread when you know you won’t want to wait for it with pthread_join(). The only performance benefit is that when a detached thread terminates, its resources can be released immediately instead of having to wait for the thread to be joined before the resources can be released. It is ‘legal’ not to … Read more

How to print pthread_t

This will print out a hexadecimal representation of a pthread_t, no matter what that actually is: void fprintPt(FILE *f, pthread_t pt) { unsigned char *ptc = (unsigned char*)(void*)(&pt); fprintf(f, “0x”); for (size_t i=0; i<sizeof(pt); i++) { fprintf(f, “%02x”, (unsigned)(ptc[i])); } } To just print a small id for a each pthread_t something like this could … Read more

sem_init on OS X

Unnamed semaphores are not supported, you need to use named semaphores. To use named semaphores instead of unnamed semaphores, use sem_open instead of sem_init, and use sem_close and sem_unlink instead of sem_destroy.