Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tips to write thread-safe UNIX code?

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 Answers

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
like image 109
D.Shawley Avatar answered Apr 12 '26 16:04

D.Shawley


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.

like image 32
Stephen Avatar answered Apr 12 '26 16:04

Stephen