There are two basic models of single-machine concurrent programming: "Messaging" and "Shared memory"; Distributed systems run on multiple machines with only one practical model: messaging.
Multi-process concurrency on a single machine can be copied "message passing", multi-threaded programming with "message delivery" easier to ensure the correctness of the program.
Multi-threaded synchronization has many ways: mutexes, conditional variables, semaphores, read-write locks, and so on. Try not to use semaphores and read-write locks
Don ' t use a semaphore where a mutex would suffice. A semaphore is a generic synchronization primitive originally described by Dijkstra so can be used to effect a wide rang E of behavior. It may tempting to use semaphores in lieu of mutexes to protect critical sections, but there was an important difference Between the Constructs:unlike a semaphore, a mutex has a notion of ownership-the Lock is either owned or no T, and if it is the owned, it has a known owner. By contrast, a semaphore (and its kin, the condition variable) have no notion of ownership:when sleeping on a semaphor E, one has no to the knowing which thread one is blocking upon. (from Real-world Concurrency http://queue.acm.org/detail) . cfm?id=1454462)
Another problem with semaphores is that it has its own count value, and usually our own data structure has a length value, which results in two copies of the same information, which needs to be consistent at all times, adding to the burden of programmers and the possibility of errors.
mutexes and condition variable are used the most, with both of them enough to handle most of the usage scenarios.
Mutex Mutex
Principle:
1. Use Raii to automatically create, destroy, locking, unlock, and do not call the lock () unlock () function manually.
2. Use thread synchronization only, without cross-process mutexes.
3. Preferred non-recursive mutex (not reentrant). Attached: The critical_section of Windows is reentrant, and the mutex under Linux is not reentrant by default. The advantage of non-reentrant mutexes is that locking the non-recursive mutex multiple times on the same line thread leads to a deadlock immediately, which helps us to think about the evaluated compile of the code to the lock and discovers the problem early (in the coding phase).
Multithreading Synchronization Essentials