开发者

Tips to write thread-safe UNIX code?

What are the guidelines to write th开发者_JAVA百科read-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?


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:

  • Lock inversion deadlocks
  • Priority inversion - if you are interested in a real life scenario, then read this snippet about the Mars Pathfinder


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜