Linux - inter-process communication of the semaphore

Introduction to Fundamental Concepts

Multiple threads access a shared data, is likely to cause adverse consequences; To ensure the integrity and security of data access to resources, the need for thread "Sync"
(Linux implementation of all the entities referred to as task (task), each task is similar to single-threaded process, with multiple tasks share a memory space constitutes a process)
 

  • Synchronization
    refers to the time a thread access to data is not completed, other threads can not access the same data, access data will atomization
     
  • Atomic operations
    indivisible, it will not be interrupted thread scheduling operations
    process (a program running might be a higher priority thread interrupts, but some operations are not interrupted, otherwise the consequences will not be restored at this time OS requires atomic operations)

Thread Synchronization

The most common way to sync before "lock" each thread to access data or resources must first acquire the lock and the lock is released after the visit; attempting to acquire a lock when the lock is occupied, the thread will wait until the lock is available again
two yuan semaphore is the simplest kind of lock, a thread is suitable for exclusive access to resources. It has only two states, occupied and unoccupied; When a thread acquires the lock, other threads trying to acquire the lock will go into wait until the lock is released.
 
Mutex amount similar to binary flag, the resource allow only one thread to access, except that the amount of signals throughout the system allows any thread to acquire and release, i.e., the semaphore may be a thread acquired the system, then by another thread release it; and which thread mutex mutex acquisition requirements, this thread will be responsible for releasing the lock, other threads release the mutex is invalid

  • Critical resource
    access only allows a process to access a resource called the critical resource, usually control critical resources with a mutex
     

P (test) / V (increase) operation

To allow multiple threads to concurrently access a semaphore lock to become polyols, referred to the amount of the signal, an initial value N semaphore allows concurrent access N threads, the thread first obtains access to the resource semaphore, the following steps (P):

  1. Save the value of the semaphore 1
  2. If the semaphore's value is less than 0, the process proceeds to wait

 
After his visit to the resource, the thread releases the semaphore, the following steps (V):

  1. The semaphore value plus 1
  2. If a wait semaphore value is less than 1, wake up threads
     

Guess you like

Origin www.cnblogs.com/chenxinshuo/p/11932969.html