Advanced Programming in UNIX environment-mutex lock, read/write lock, and condition variable for thread synchronization (Summary)

Source: Internet
Author: User

I. Use mutex lock

1. initialize mutex

Pthread_mutex_t mutex = pthread_mutex_initializer; // static initialization mutex
Int pthread_mutex_init (pthread_mutex_t * mutex, pthread_mutexattr_t * ATTR); // dynamically initialize mutex
Int pthread_mutex_destory (pthread_mutex_t * mutex); // cancel a mutex. You cannot copy a mutex variable, but you can copy a pointer to the mutex, in this way, multiple functions or threads can share the mutex for synchronization. The mutex quantity applied for dynamically above must be dynamically revoked.

2. Lock and unlock mutex

Int pthread_mutex_lock (pthread_mutex_t * mutex );
Int pthread_mutex_trylock (pthread_mutex_t * mutex );
Int pthread_mutex_unlock (pthread_mutex_t * mutex );

When pthread_mutex_lock is called to lock the mutex, if the mutex is locked, the calling thread is blocked. The pthread_mutex_trylock function returns the error code ebusy when the call mutex is locked. Like a semaphore, lock mutex before processing shared data, and finally unlock mutex.
The sample code in the semaphore is modified as follows:

# Include<Pthread. h>
# Include<Stdio. h>
# Include<Semaphore. h>
# DefineNiters
100000000
/* Shared variable */
Unsigned
IntCNT =
0; // sem_t mutex;
Pthread_mutex_t mutex; Void
* Count ( Void
* Arg)
{
IntI;
For(I = 0; I <niters; I ++)
{
Pthread_mutex_lock (& mutex );
CNT ++;
Pthread_mutex_unlock (& mutex );
}
ReturnARG;
} IntMain ()
{
Pthread_t tid1, tid2;
IntStatus;
Pthread_mutex_init (& mutex, null );

Pthread_mutex_destroy (& mutex );
If(CNT! = ( Unsigned) Niters * 2)
Printf ("Boom !, CNT = % d \ n ", CNT );
Else
Printf ("OK CNT = % d \ n", CNT ); Return
0;
}

3. Use multiple mutex

Deadlock may occur when multiple mutex values are used. As follows:

Thread 1 thread 2

Pthread_mutex_lock (& mutex_a); pthread_mutex_lock (& mutex_ B );

Pthread_mutex_lock (& mutex_ B); pthread_mutex_lock (& mutex_a );

When both threads complete the first step, neither of them can complete the second step, causing a deadlock. The following two methods can be used to avoid deadlocks:

Fixed lock layers: all codes that require simultaneous lock of mutex A and mutex B must first lock a and then lock B.

Try to lock and roll back: After locking the first mutex, use pthread_mutex_trylock to lock other mutex. If the lock fails, release the mutex that has been locked and re-lock it.

 

 

Ii. Use the read/write lock

The read/write lock can be used to concurrently read and write data to protected shared resources exclusively. A read/write lock is a single entity that can be locked in read or write mode. To modify resources, the thread must first obtain the mutex write lock. You must release all read locks before using mutex.

1. Initialization and destruction:

# Include <pthread. h>
Int pthread_rwlock_init (pthread_rwlock_t * restrict rwlock, const pthread_rwlockattr_t * restrict ATTR );
Int pthread_rwlock_destroy (pthread_rwlock_t * rwlock );

Like mutex, before releasing the memory occupied by read/write locks, you must use pthread_rwlock_destroy to clear the read/write locks and release the resources allocated by init.

2. Lock and unlock

Read the lock in the read/write lock IntPthread_rwlock_rdlock (pthread_rwlock_t
* Rwlock );

Read locks from non-blocking read/write locksIntPthread_rwlock_tryrdlock (pthread_rwlock_t
* Rwlock );

Lock used to write a read/write lockIntPthread_rwlock_wrlock (pthread_rwlock_t
* Rwlock );

Write locks in non-blocking read/write locksIntPthread_rwlock_trywrlock (pthread_rwlock_t
* Rwlock );

Unlock read/write locksIntPthread_rwlock_unlock (pthread_rwlock_t
* Rwlock );

 

3. Condition Variables

If a thread needs to wait for the system to be in a certain state before it can continue to run, in order to solve this problem, Linux introduces the thread synchronization object, the condition variable is used to notify the shared data status information, the wait condition variable always returns the lock mutex. The condition variable is a signal mechanism related to mutex and shared data protected by mutex.

Conditional variables do not provide mutex. A mutex is required to synchronize access to shared data, which is why a mutex must be specified while waiting for the conditional variable.

1. create and destroy condition Variables

# Include <pthread. h>
Pthread_cond_t cond = pthread_cond_initializer;
Int pthread_cond_init (pthread_cond_t * restrict cond, const pthread_condattr_t * restrict ATTR );
Int pthread_cond_destroy (pthread_cond_t * Cond );

2. Waiting condition variable # include <pthread. h>
Int pthread_cond_timedwait (pthread_cond_t * restrict cond, pthread_mutex_t * restrict mutex, const struct timespec * restrict abstime );
Int pthread_cond_wait (pthread_cond_t * restrict cond, pthread_mutex_t * restrict mutex );

The difference between the two functions is that the former specifies a timeout time, blocks the call thread within the time, and waits for the condition variable. If the condition has not occurred within the specified time, the function returns. Each condition variable must be associated with a specific mutex. When a thread waits for a condition variable, it must lock the related mutex. Before the thread is blocked, the conditional variable waits for the Operation to unlock the mutex, and before returning the thread again, the mutex is locked for the next time.

3. Wake up the conditional variable wait thread # include <pthread. h>
Int pthread_cond_broadcast (pthread_cond_t * Cond );
Int pthread_cond_signal (pthread_cond_t * Cond); pthread_cond_signal will activate one of the waiting threads; pthread_cond_broadcast will activate all threads. In addition, note that these two functions also require mutex protection.

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.