Linux multithreaded Programming--thread synchronization and mutual exclusion

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.