UNIX Environment Advanced Programming: Mutex, read-write lock, and condition variable for thread synchronization

Source: Internet
Author: User
Tags error code mutex printf semaphore thread

First, the use of mutual exclusion locks

1, the initialization of mutual exclusion

The pthread_mutex_t mutex =pthread_mutex_initializer;//statically initializes the mutex  
int pthread_mutex_init (Pthread_mutex_t*mutex, PTHREAD_MUTEXATTR_T*ATTR)//dynamic initialization Mutex  
int pthread_mutex_destory (PTHREAD_MUTEX_T*MUTEX);/Undo Mutex

You cannot copy a mutex variable, but you can copy a pointer to a mutex so that multiple functions or threads can share the mutex to achieve synchronization. The mutex that is dynamically requested above requires a dynamic revocation.

2, lock and unlock mutually exclusive amount

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 a pthread_mutex_lock lock mutex is invoked, the calling thread is blocked if the mutex is already locked. The Pthread_mutex_trylock function returns an error code ebusy when the calling mutex is already locked. Using the same as the semaphore, lock the mutex before processing the shared data, and finally unlock the mutex.

Modified for the example on the upper semaphore:

#include <pthread.h>  
#include <stdio.h>  
#include <semaphore.h>  
#define Niters 100000000  
/* Shared variable *
/unsigned int cnt = 0;  
Sem_t Mutex;  
pthread_mutex_t Mutex;  
void *count (void *arg)  
{  
    int i;  
    for (i=0;i<niters;i++)  
    {  
        pthread_mutex_lock (&mutex);  
        cnt++;  
        Pthread_mutex_unlock (&mutex);  
    }  
    return arg;  
}  
int main ()  
{  
    pthread_t tid1,tid2;  
    int status;  
    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. Using multiple mutexes

Using multiple mutexes can cause a deadlock problem. 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 two threads complete the first step, the second step cannot be completed, resulting in a deadlock. There are two ways to avoid deadlocks:

Fixed lock level: All code that needs to lock both mutex A and mutex B at the same time, must lock A and lock B first.

Try lock and rollback: After locking the first mutex, use Pthread_mutex_trylock to lock the other mutex, and if it fails, releases the locked mutex and locks it again.

See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/OS/unix/

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.