Using a shared variable directly, it is very clumsy and inefficient to switch between two threads;
Signal Volume--
Mutex Amount--
The two are realized by each other through each other;
For example, if you want to control a moment only one thread can access some shared memory, it is natural to use mutex;
But when controlling a set of identical pairs of accesses, allocating 1 to an available thread, compared to 5 available phone lines, the count semaphore is used;
-------------------------------------
Semaphore, is a special type of variable, it can be increased or decreased, but the key access to it is guaranteed to be atomic operation, in time a multithreaded procedure is also as comparable;
means that if two (more) of the field attempts to change the value of a semaphore, the system guarantees that all operations will be performed at once
The semaphore, the binary signal quantity only has 0/1 two kinds of values, also has a more general signal quantity--counts the signal quantity;
The name of the semaphore function starts with sem_, not the Pthread_, as most thread functions do
There are four basic semaphore functions:
---
#include <semaphore.h>
int Sem_init (sem_t *sem,int psthared, unsigned int value);
The semaphore is created by this function, the semaphore object that the SEM points to, set his shared parameters, give an initial integer value
Psthared, the type of control semaphore, whose value is 0, indicates that the semaphore is the local semaphore of the current process, otherwise the semaphore can be shared across multiple processes
---
#include <semaphore.h>
int sem_wait (sem_t *sem);
The wait function will reduce the semaphore to 1, but will wait until the new two has a non-0 value to start the subtraction operation;
If you call the Sem_wait function on a semaphore that is 0, the function waits, knowing that the other thread has added the semaphore value to make it! = 0;
---
#include <semaphore.h>
int Sem_post (sem_t *sem);
The post function is the value of the semaphore in atomic Operation +1;
Description: The ability to atomically test and set in a single function is valuable;
---
Sem_trywait () is a non-blocking version of Sem_wait
Clears all resources owned by a semaphore pointer as a parameter, and if an attempt to clean up the semaphore is being waited by a thread, an error is returned
---
#include <semaphore.h>
int Sem_destroy (sem_t *sem);
==============
Example
[Linux Basic Basics]----synchronization