Wake up thread blocked on accept() call

Close the socket using the shutdown() call. This will wake up any threads blocked on it, while keeping the file descriptor valid. close() on a descriptor another thread B is using is inherently hazardous: another thread C may open a new file descriptor which thread B will then use instead of the closed one. dup2() … Read more

Does guarding a variable with a pthread mutex guarantee it’s also not cached?

pthread locks implement memory barriers that will ensure that cache effects are made visible to other threads. You don’t need volatile to properly deal with the shared variable i if the accesses to the shared variable are protected by pthread mutexes. from http://www.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_11: The following functions synchronize memory with respect to other threads: fork() pthread_barrier_wait() … 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.

POSIX threads and signals

What’s the best way to control which thread a signal is delivered to? As @zoli2k indicated, explicitly nominating a single thread to handle all signals you want handled (or a set of threads each with specific signal responsibilities), is a good technique. What is the best way to tell another thread (that might actually be … Read more

mingw-w64 threads: posix vs win32

GCC comes with a compiler runtime library (libgcc) which it uses for (among other things) providing a low-level OS abstraction for multithreading related functionality in the languages it supports. The most relevant example is libstdc++’s C++11 <thread>, <mutex>, and <future>, which do not have a complete implementation when GCC is built with its internal Win32 … Read more

Calling pthread_cond_signal without locking mutex

If you do not lock the mutex in the codepath that changes the condition and signals, you can lose wakeups. Consider this pair of processes: Process A: pthread_mutex_lock(&mutex); while (condition == FALSE) pthread_cond_wait(&cond, &mutex); pthread_mutex_unlock(&mutex); Process B (incorrect): condition = TRUE; pthread_cond_signal(&cond); Then consider this possible interleaving of instructions, where condition starts out as FALSE: … Read more

Why does pthread_cond_wait have spurious wakeups?

There are at least two things ‘spurious wakeup’ could mean: A thread blocked in pthread_cond_wait can return from the call even though no call to pthread_call_signal or pthread_cond_broadcast on the condition occurred. A thread blocked in pthread_cond_wait returns because of a call to pthread_cond_signal or pthread_cond_broadcast, however after reacquiring the mutex the underlying predicate is … Read more