Thread synchronization mechanism for Linux under C

Source: Internet
Author: User
Tags mutex posix semaphore

The three ways to ensure thread safety are provided in C:

(Add header file #include<pthread.h>,pthread Library is not the default library of Linux system, need to use static library libpthread.a when connecting, add-lpthread parameter in compiling)

    • Mutual exclusion Lock

By locking mechanism to achieve mutual exclusion between threads, only one thread at a time can lock it, when a lock is locked by a thread, if another thread tries to lock the critical section (mutex), then the second thread will be blocked , or put in a wait state. The second thread can resume running from the blocking state only if the first thread releases a lock on the critical section.

int Pthread_mutex_init (pthread_mutex_t* Mutex, const thread_mutexattr_t* mutexattr); Initializes a mutex.

int Pthread_mutex_lock (pthread_mutex_t* mutex); If the mutex is locked, the current process is in a wait state; otherwise, the process obtains the mutex and enters the critical section.

int Pthread_mutex_trylock (pthread_mutex_t* mutex); Unlike lock, attempting to obtain a mutex is unsuccessful and will not cause the process to go into a blocking state, but continues to return to the thread execution. This function can effectively avoid the loop wait lock, if the Trylock failure can release the resources already occupied, this can avoid deadlock.

int Pthread_mutex_unlock (pthread_mutex_t* mutex); Releases the mutex and causes the blocked thread to obtain the mutex and execute.

int Pthread_mutex_destroy (pthread_mutex_t* mutex); The resource used to revoke the mutex.

pthread_mutex_t mutex;pthread_mutex_init (&mutex,null); void pthread1 (void* arg) {   pthread_mutex_lock (&mutex);   ..... // critical Section   Pthread_mutex_unlock (&Mutex);} void pthread2 (void* arg) {   pthread_mutex_lock (&mutex);   ..... // critical Section   Pthread_mutex_unlock (&Mutex);}
    • Read/write Lock

Read and write locks are similar to mutexes, but read-write locks allow for higher parallelism. A data structure that is suitable for reading times greater than the number of writes.

Only one thread at a time can occupy write-mode read-write locks, but multiple threads can occupy read-mode reading and writing locks at the same time.

Read lock lock, read lock, can be, write lock will be blocked, but this will block the subsequent read lock request, prevent read lock long-term consumption cannot enter write mode. A write lock is a mutual exclusion lock.

int Pthread_rwlock_init (pthread_rwlock_t* rwlock, const pthread_rwlockattr_t* attr); Initialize read-write lock

int Pthread_destroy (pthread_rwlock_t* rwlock); Destroy read-write lock

int Pthread_rwlock_rdlock (pthread_rwlock_t* rwlock); Read lock

int Pthread_rwlock_wrlock (pthread_rwlock_t* rwlock); add write lock

int Pthread_rwlock_unlock (pthread_rwlock_t* rwlock), unlocking

    • Condition variable

Semaphores are locked and unlocked in both states, and are allowed to wait for a particular condition to occur in a non-competitive manner when the condition variable and semaphore are used together.

The condition itself is protected by a mutex: the thread must lock the mutex before changing the condition state.

int Pthread_cond_init (pthread_cond_t* cond,const pthread_condattr_t* attr); initialize dynamically assigned condition variables; You can also use Pthread_ directly Initializer direct assignment to a static condition variable

int Pthread_cond_destroy (pthread_cond_t* cond) revokes the conditional variable resource;

int pthread_cond_wait (pthread_cond_t* cond, pthread_mutex_t* mutex); Use this function to make the wait condition variable true. The thread is blocked by the condition variable cond.

int pthread_cond_timedwait (pthread_cond_t* cond, pthread_mutex_t* mutex,const struct timespec* TSPR); Similar to wait, Just after the TSPR time, even if the condition variable is not satisfied, the block is lifted and the error code is returned.

int pthread_cond_signal (pthread_cond_t* cond); Wakes the thread because the condition variable is blocked.

int Pthread_cond_broadcast (pthread_cond_t* cond); Wakes all threads waiting for the condition.

  

pthread_cond_t cond;pthread_mutex_t Mutex;intCount=0;voidPthread1 (void*Arg) {Pthread_mutex_lock (&mutex);  while(count==0) pthread_cond_wait (&cond,&mutex); Count--; Pthread_mutex_unlock (&mutex);}voidPthread2 (void*Arg) {Pthread_mutex_lock (&mutex); if(count==0) pthread_cond_signal (&cond); Count++; Pthread_mutex_unlock (&mutex);}
    • Spin lock

The mutex blocks the thread by getting it to sleep, and the spin lock is to keep the thread busy and so on, i.e. it does not sleep, but keeps on judging that the spin lock has been unlocked.

It is suitable for the case that the spin lock time is shorter.

    • Signal Volume

Introducing POSIX (the POSIX standard defines the interface standards that the operating system should provide for applications, in other words, programs written for a POSIX-compliant operating system should be compiled on any other POSIX operating system, even from another vendor). ) The semaphore mechanism, defined in the header file/usr/include/semaphore.h

1) Initialization of a semaphore: Sem_init ()

int Sem_init (sem_t* sem,int pshared,unsigned int value);

A pshared of 0 indicates that the semaphore can only be shared between threads of the current process, otherwise it can be shared between processes, and value gives the initial value of the semaphore.

2) Blocking Threads

Sem_wait (sem_t* sem) until the value of the signal volume SEM is greater than 0, the value of SEM is reduced by one after unblocking, indicating that the public resource decreases after use; Sem_trywait (sem_t* SEM) is a non-blocking version of wait, which directly reduces the value of the SEM by one, Equivalent to P operation.

3) Increase the value of the semaphore, wake up the thread

Sem_post (sem_t* sem) causes one of the threads that have been blocked to stop blocking, and the selection mechanism is also determined by the thread's scheduling policy. Equivalent to V operation.

3) Releasing the semaphore resource

Sem_destroy (sem_t* sem) is used to release the resources of the signal volume SEM

pthread_mutex_t mutex;sem_t full,empty;voidProducervoid*Arg) {     while(1) {sem_wait (&empty);//need to produce. The empty of resource need minus 1Pthread_mutex_lock (&mutex); ...//produce a resourcePthread_mutex_unlock (&mutex); Sem_post (&full);//has produced a resource, the full of resource need add 1    }}voidConsumervoid*Arg) {     while(1) {sem_wait (&Full ); Pthread_mutex_lock (&mutex); ...//consume a resourcePthread_mutex_unlock (&mutex); Sem_post (&empty); }}

Thread synchronization mechanism for Linux under C

Related Article

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.