zoukankan      html  css  js  c++  java
  • Linux多线程同步之相互排斥量和条件变量

    1. 什么是相互排斥量

           相互排斥量从本质上说是一把锁,在訪问共享资源前对相互排斥量进行加锁,在訪问完毕后释放相互排斥量上的锁。

    对相互排斥量进行加锁以后,不论什么其它试图再次对相互排斥量加锁的线程将会被堵塞直到当前线程释放该相互排斥锁。假设释放相互排斥锁时有多个线程堵塞,所以在该相互排斥锁上的堵塞线程都会变成可进行状态。第一个变成执行状态的线程能够对相互排斥量加锁。其它线程在次被堵塞,等待下次执行状态。

    pthread_mutex_t 就是POSIX对于mutex的实现。

    函数名 參数 说明
    pthread_mutex_init

    pthread_mutex_t * mutex,

    constpthread_mutex_t *attr
    初始化一个相互排斥量,静态方式能够直接使用PTHREAD_MUTEX_INITIALIZER进行赋值初始化
    pthread_mutex_destroy pthread_mutex_t *mutex 释放对相互排斥变量分配的资源。注意pthread_mutex_init有可能malloc了资源
    pthread_mutex_lock pthread_mutex_t *mutex 假设相互排斥量已经上锁,调用线程堵塞直至相互排斥量解锁
    pthread_mutex_trylock pthread_mutex_t *mutex 加锁。假设失败不堵塞
    pthread_mutex_unlock pthread_mutex_t *mutex 解锁
    使用init函数进行初始化:

    [cpp] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. #include <pthread.h>  
    2.   
    3. pthread_mutex_t foo_mutex;  
    4.   
    5. void foo()  
    6. {  
    7.   pthread_mutex_init(&foo_mutex, NULL);  
    8.   pthread_mutex_lock(&foo_mutex);  
    9.   /* Do work. */  
    10.   pthread_mutex_unlock(&foo_mutex);  
    11.   pthread_mutex_destroy(&foo_mutex);  
    12. }  


    当然该初始化

    [cpp] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. pthread_mutex_init(&foo_mutex, NULL);  

    仅仅能foo_mutex使用前初始化一次。最后destroy。

    初始化已经初始化的mutex将导致undefined behavior。

    第二种使用方法:

    [cpp] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. pthread_mutex_t foo_mutex = PTHREAD_MUTEX_INITIALIZER;  
    2. void foo()  
    3. {  
    4.   pthread_mutex_lock(&foo_mutex);  
    5.   /* Do work. */  
    6.   pthread_mutex_unlock(&foo_mutex);  
    7. }  

    当然了,这两种使用方法都有问题:假设在lock住后unlock之前出现exception,那么这个锁永远也不能unlock。

    这样的情况下须要guard这个资源。详细可參照boost::mutex::scoped_lock的实现,很easy可是极大简化了mutex的安全使用。

    2. 什么是条件变量

          与相互排斥锁不同,条件变量是用来等待而不是用来上锁的。

    条件变量用来自己主动堵塞一个线程,直到某特殊情况发生为止。通常条件变量和相互排斥锁同一时候使用。

          条件变量使我们能够睡眠等待某种条件出现。

    条件变量是利用线程间共享的全局变量进行同步的一种机制,主要包含两个动作:一个线程等待"条件变量的条件成立"而挂起;还有一个线程使"条件成立"(给出条件成立信号)。

         条件的检測是在相互排斥锁的保护下进行的。

    假设一个条件为假,一个线程自己主动堵塞,并释放等待状态改变的相互排斥锁。假设还有一个线程改变了条件,它发信号给关联的条件变量,唤醒一个或多个等待它的线程。又一次获得相互排斥锁,又一次评价条件。假设两进程共享可读写的内存,条件变量能够被用来实现这两进程间的线程同步。

          条件变量的初始化和mutex的初始化差点儿相同,也是有两种方式:

              pthread_cond_tmy_condition=PTHREAD_COND_INITIALIZER;

              也能够利用函数pthread_cond_init动态初始化。

    以下中各个函数的简单介绍。

    函数名 參数 说明
    pthread_cond_init pthread_cond_t *cond, 
    const pthread_condattr_t *attr
    初始化
    pthread_cond_destroy pthread_cond_t *cond 回收
    pthread_cond_wait pthread_cond_t *cond,
    pthread_mutex_t *mutex
    等待。无超时
    pthread_cond_timedwait pthread_cond_t *cond,pthread_mutex_t *mutex,
    const struct timespec *abstime
    等待。有超时
    pthread_cond_signal pthread_cond_t *cond 一个在同样条件变量上堵塞的线程将被解锁。假设同一时候有多个线程堵塞,则由调度策略确定接收通知的线程
    pthread_cond_broadcast pthread_cond_t *cond 将通知堵塞在这个条件变量上的全部线程。一旦被唤醒,线程仍然会要求相互排斥锁。


    一个简单使用条件变量进行线程同步的小样例:

    /*
     * pthread_mutex_cond.c
     *
     */
    
    #include <pthread.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
    pthread_cond_t cond =  PTHREAD_COND_INITIALIZER;
    int i = 0;
    
    void *thread1(void *);
    void *thread2(void *);
    
    int main(void)
    {
    	pthread_t tid1, tid2;
    	if(pthread_create(&tid1, NULL, thread1, NULL))
    		exit(1);
    	if(pthread_create(&tid2, NULL, thread2, NULL))
    		exit(1);
    	if(pthread_join(tid1, NULL))
    		exit(1);
    	printf("thread1 exit
    ");
    	if(pthread_join(tid2, NULL))
    		exit(1);
    	printf("thread2 exit
    ");
    
    	pthread_mutex_destroy(&mutex);
    	pthread_cond_destroy(&cond);
    	exit(0);
    }
    
    void *thread1(void *arg)
    {
    	printf("thread1 start
    ");
    	while(i <= 6)
    	{
    		pthread_mutex_lock(&mutex);
    		printf("thread1: lock %d
    ", __LINE__);
    		printf("thread1 i = %d
    ", i);
    		if(i%3 == 0)
    		{
    			printf("thread1:signal 1  %d
    ", __LINE__);
    			pthread_cond_signal(&cond);
    			printf("thread1:signal 2  %d
    ", __LINE__);
    		}
    		pthread_mutex_unlock(&mutex);
    		printf("thread1: unlock %d
    ", __LINE__);
    		sleep(1);	//sleep 1s,让线程2得以运行
    		i++;
    	}
    	pthread_exit((void *)0);
    }
    
    void *thread2(void *arg)
    {
    	//sleep(1);
    	printf("thread2 start
    ");
    	while(i <= 6)
    	{
    		pthread_mutex_lock(&mutex);
    		printf("thread2: lock %d
    ", __LINE__);
    		printf("thread2 i = %d
    ", i);
    		if(i%3 != 0)
    		{
    			 printf("thread2: wait 1  %d
    ", __LINE__);
    			 pthread_cond_wait(&cond, &mutex);
    			 printf("thread2: wait 2  %d
    ", __LINE__);
    		}
    
    		pthread_mutex_unlock(&mutex);
    		printf("thread2: unlock %d
    ", __LINE__);
    		sleep(1);	//sleep 1s。让线程1得以运行
    	}
    	pthread_exit((void *)0);
    }
    
    运行结果:

    thread2 start
    thread2: lock 65
    thread2 i = 0
    thread2: unlock 75
    thread1 start
    thread1: lock 42
    thread1 i = 0
    thread1:signal 1  46
    thread1:signal 2  48
    thread1: unlock 51
    thread2: lock 65
    thread2 i = 0
    thread2: unlock 75
    thread1: lock 42
    thread1 i = 1
    thread1: unlock 51
    thread2: lock 65
    thread2 i = 1
    thread2: wait 1  69
    thread1: lock 42
    thread1 i = 2
    thread1: unlock 51
    thread1: lock 42
    thread1 i = 3
    thread1:signal 1  46
    thread1:signal 2  48
    thread1: unlock 51
    thread2: wait 2  71
    thread2: unlock 75
    thread2: lock 65
    thread2 i = 3
    thread2: unlock 75
    thread1: lock 42
    thread1 i = 4
    thread1: unlock 51
    thread2: lock 65
    thread2 i = 4
    thread2: wait 1  69
    thread1: lock 42
    thread1 i = 5
    thread1: unlock 51
    thread1: lock 42
    thread1 i = 6
    thread1:signal 1  46
    thread1:signal 2  48
    thread1: unlock 51
    thread2: wait 2  71
    thread2: unlock 75
    thread2: lock 65
    thread2 i = 6
    thread2: unlock 75
    thread1 exit
    thread2 exit

    生产者-消费者的实现


    该问题描写叙述了两个共享固定大小缓冲区的线程——即所谓的“生产者”和“消费者”——在实际执行时会发生的问题。
    要求:当工作队列为空时,消费者不能从工作队列取走数据,直到工作队列有数据时才干够。
    本例中用一个单链表来模拟工作队列。生产者生产一个结构体串在链表的表头上,消费者从表头取走结构体。在两个线程里分别计数。生产者生产6次,消费者消费6次。

    /*
     * producer-consumer.c
     *
     */
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <pthread.h>
    
    struct msg{
    	struct msg *next;
    	int num;
    };
    
    struct msg *head;	//共享资源,全局指针初始化为NULL
    pthread_cond_t has_product = PTHREAD_COND_INITIALIZER;
    pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
    
    void *consumer(void *);
    void *producer(void *);
    
    int main(void)
    {
    	pthread_t tid1,tid2;
    	int res;
    
    	srand(time(NULL));
    	res = pthread_create(&tid1,NULL,producer,NULL);
    	if(res != 0)
    	{
    		perror("thread producer create failed
    ");
    		exit(1);
    	}
    	res = pthread_create(&tid2,NULL,consumer,NULL);
    	if(res != 0)
    	{
    		perror("thread consumer create failed
    ");
    		exit(1);
    	}
    	pthread_join(tid1,NULL);
    	if(res != 0)
    	{
    		perror("join thread producer failed
    ");
    		exit(1);
    	}
    	printf("thread producer exit
    ");
    	pthread_join(tid2,NULL);
    	if(res != 0)
    	{
    		perror("join thread consumer failed
    ");
    		exit(1);
    	}
    	printf("thread consumer exit
    ");
    
    	pthread_mutex_destroy(&mutex);
    	pthread_cond_destroy(&has_product);
    	exit(0);
    }
    
    void *producer(void *arg)
    {
    	struct msg *mp;
    	int i;
    	printf("producer thread start
    ");
    	for(i=0;i<6;i++)
    	{
    		printf("producer i = %d
    ", i);
    		mp = (struct msg *)malloc(sizeof(struct msg));
    		mp->num = rand()%100 + 1;
    		printf("Produce %d
    ", mp->num);
    		pthread_mutex_lock(&mutex);
    		mp->next = head;
    		head = mp;	//生产者生产一个结构体串在链表的表头上
    		pthread_mutex_unlock(&mutex);
    		pthread_cond_signal(&has_product);
    		sleep(1);	//让还有一个线程有机会运行
    	}
    	pthread_exit(NULL);
    }
    
    void *consumer(void *arg)
    {
    	struct msg *con;
    	int i;
    	printf("consumer thread start
    ");
    	for(i=0;i<6;i++)
    	{
    		printf("consumer i = %d
    ", i);
    		pthread_mutex_lock(&mutex);
    		while(head == NULL)
    		{
    			printf("struct msg is null
    ");
    			pthread_cond_wait(&has_product,&mutex);
    		}
    		con = head;	//消费者从表头取走结构体
    		head = con->next;
    		pthread_mutex_unlock(&mutex);
    		printf("Consume %d
    ", con->num);
    		free(con);
    		sleep(1);	//让还有一个线程有机会运行
    	}
    	pthread_exit(NULL);
    }
    
    运行结果:

    consumer thread start
    consumer i = 0
    struct msg is null
    producer thread start
    producer i = 0
    Produce 52
    Consume 52
    consumer i = 1
    struct msg is null
    producer i = 1
    Produce 33
    Consume 33
    consumer i = 2
    struct msg is null
    producer i = 2
    Produce 77
    Consume 77
    consumer i = 3
    struct msg is null
    producer i = 3
    Produce 86
    Consume 86
    consumer i = 4
    struct msg is null
    producer i = 4
    Produce 84
    Consume 84
    consumer i = 5
    struct msg is null
    producer i = 5
    Produce 46
    Consume 46
    thread producer exit
    thread consumer exit

  • 相关阅读:
    lunix下的redis数据库操作——set集合
    lunix下的redis数据库操作——hash(哈希)
    lunix下的redis数据库操作——list列表
    python操作mysql
    linux修改mysql表结构
    关于wordclou的一些简单操作
    SQL NOW() 函数:返回当前系统的日期和时间
    SQL ROUND() 函数:把数值字段四舍五入为指定的小数位数
    SQL LEN() 函数:返回文本字段中值的长度
    SQL MID() 函数:从文本字段中提取字符
  • 原文地址:https://www.cnblogs.com/yfceshi/p/7383732.html
Copyright © 2011-2022 走看看