Preface: Whether it is multithreaded programming or multi-process programming, it is necessary to control the synchronization and mutex issues between different threads or processes. Synchronization is a task that is performed by multiple processes or threads together, for example, a buffer producer and consumer problem, when the producer produces a commodity, the waiting consumer gets a message that the goods can be taken away, and when the consumer takes a commodity, the producer knows that it can continue to produce a commodity, This is a synchronization problem, the so-called mutex problem, refers to a shared resource in a single operation, can only be occupied by one thread or process, other threads or processes can not operate on it, such as a read and write operation of a shared memory, when a process writes to it, another process can not read it, otherwise it may cause data inconsistency.
Mutex Amount
The mutex is quite the same as the lock, when the shared resource is used, it is locked, when it is used, the lock is freed, and other threads cannot operate on the shared resource during the lock.
Data type: pthread_mutex_t
Related APIs
Initializing and destroying mutexes
INT Pthread_mutex_init (pthread_mutext_t *restrict Mutex, const pthread_mutexattr_t *restrict attr),//attr set to NULL, Represents the default property to initialize the mutex amount
int Pthread_mutex_destroy (pthread_mutex_t *mutex);
Locking
int Pthread_mutex_lock (pthread_mutex_t *mutex); Lock the mutex, if the mutex is locked, it will block until the semaphore is unlocked, and successfully returns 0.
int Pthread_mutex_trylock (pthread_mutex_t *mutex);//If the semaphore is not locked, lock and return 0, if the signal is locked, it will not block, return a non-0 value
int Pthread_mutex_unlock (pthread_mutex_t *mutex);//unlock
Linux multithreaded Programming--thread synchronization and mutual exclusion