Implementing a FIFO mutex in pthreads

You can implement a fair queuing system where each thread is added to a queue when it blocks, and the first thread on the queue always gets the resource when it becomes available. Such a “fair” ticket lock built on pthreads primitives might look like this: #include <pthread.h> typedef struct ticket_lock { pthread_cond_t cond; pthread_mutex_t … Read more

Does pthread_mutex_lock contains memory fence instruction? [duplicate]

Do pthread_mutex_lock and pthread_mutex_unlock functions call memory fence/barrier instructions? They do, as well as thread creation. Note, however, there are two types of memory barriers: compiler and hardware. Compiler barriers only prevent the compiler from reordering reads and writes and speculating variable values, but don’t prevent the CPU from reordering. The hardware barriers prevent the … Read more

Is accept() thread-safe?

Yes. This is a common way to design multithreaded servers and accepted design practice. You can also fork several times and have the child processes call accept, this will allow you to do multithreading without needing a threads library. Older servers do this.

When to use pthread condition variables?

Condition variables should be used as a place to wait and be notified. They are not the condition itself and they are not events. The condition is contained in the surrounding programming logic. The typical usage pattern of condition variables is // safely examine the condition, prevent other threads from // altering it pthread_mutex_lock (&lock); … Read more

valgrind memory leak errors when using pthread_create

A thread’s resources are not immediately released at termination, unless the thread was created with the detach state attribute set to PTHREAD_CREATE_DETACHED, or if pthread_detach is called for its pthread_t. An undetached thread will remain terminated state until its identifier is passed to pthread_join or pthread_detach. To sum it up, you have three options: create … Read more