views:

156

answers:

4

What are the guidelines to write thread-safe UNIX code in C and C++?

I know only a few:

  • Don't use globals
  • Don't use static local storage

What others are there?

+2  A: 

It really comes down to shared state, globals and static local are examples of shared state. If you don't share state, you won't have a problem. Other examples of shared state include multiple threads writing to a file or socket.

Any shared resource will need to be managed properly - that might mean making something mutex protected, opening another file, or intelligently serializing requests.

If two threads are reading and writing from the same struct, you'll need to handle that case.

Stephen
+1  A: 

Beware of the sem_t functions, they may return uncompleted on interrupts, IO, SIGCHLD etc. If you need them, be sure to allways capture that case.

pthread_mut_t and pthread_cond_t functions are safe with respect to EINTR.

Jens Gustedt
+3  A: 

The simple thing to do is read a little. The following list contains some stuff to look at and research.

  1. Spend time reading the Open Group Base Specification particularly the General Information section and the subsection on threads. This is the basis information for multithreading under most UN*X-alike systems.
  2. Learn the difference between a mutex and a semaphore
  3. Realize that everything that is shared MUST be protected. This applies to global variables, static variables, and any shared dynamically allocated memory.
  4. Replace global state flags with condition variables. These are implemented using pthread_cond_init and related functions.

Once you understand the basics, learn about the common problems so that you can identify them when they occur:

D.Shawley
Wow, i basically hadn't heard about anything that you listed here! Starting to read.
bodacydo
There is a lot of information out there. If you want more booklike things, give the notes at https://computing.llnl.gov/tutorials/pthreads/ a read or buy "UNIX Systems Programming" (http://www.amazon.com/UNIX-Systems-Programming-Communication-Concurrency/dp/0130424110/)
D.Shawley
A: 

A good open book about concurrency in general can be found here: Little Book of Semaphores

It presents various problems that are solved step-by step and include solutions to common concurrency issues like starvation, race conditions etc. It is not language-specific but contains short chapters about implementing the solutions in C with the Pthread-Library or Python.

baggio