【Linux C 多线程编程】互斥锁与条件变量

一、互斥锁

互斥量从本质上说就是一把锁, 提供对共享资源的保护访问。

  1. 初始化:

  在Linux下, 线程的互斥量数据类型是pthread_mutex_t. 在使用前, 要对它进行初始化:

  对于静态分配的互斥量, 可以把它设置为PTHREAD_MUTEX_INITIALIZER, 或者调用pthread_mutex_init.

  对于动态分配的互斥量, 在申请内存(malloc)之后, 通过pthread_mutex_init进行初始化, 并且在释放内存(free)前需要调用pthread_mutex_destroy.

  原型:

  int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restric attr);

  int pthread_mutex_destroy(pthread_mutex_t *mutex);

  头文件:

  返回值: 成功则返回0, 出错则返回错误编号.

  说明: 如果使用默认的属性初始化互斥量, 只需把attr设为NULL. 其他值在以后讲解。

  2. 互斥操作:

  对共享资源的访问, 要对互斥量进行加锁, 如果互斥量已经上了锁, 调用线程会阻塞, 直到互斥量被解锁. 在完成了对共享资源的访问后, 要对互斥量进行解锁。

  首先说一下加锁函数:

  头文件:

  原型:

  int pthread_mutex_lock(pthread_mutex_t *mutex);

  int pthread_mutex_trylock(pthread_mutex_t *mutex);

  返回值: 成功则返回0, 出错则返回错误编号.

  说明: 具体说一下trylock函数, 这个函数是非阻塞调用模式, 也就是说, 如果互斥量没被锁住, trylock函数将把互斥量加锁, 并获得对共享资源的访问权限; 如果互斥量被锁住了, trylock函数将不会阻塞等待而直接返回EBUSY, 表示共享资源处于忙状态。

  再说一下解所函数:

  头文件:

  原型: int pthread_mutex_unlock(pthread_mutex_t *mutex);

  返回值: 成功则返回0, 出错则返回错误编号.

  3. 死锁:

  死锁主要发生在有多个依赖锁存在时, 会在一个线程试图以与另一个线程相反顺序锁住互斥量时发生. 如何避免死锁是使用互斥量应该格外注意的东西。

  总体来讲, 有几个不成文的基本原则:

  对共享资源操作前一定要获得锁。

  完成操作以后一定要释放锁。

  尽量短时间地占用锁。

  如果有多锁, 如获得顺序是ABC连环扣, 释放顺序也应该是ABC。

  线程错误返回时应该释放它所获得的锁。

下面给个测试小程序进一步了解互斥,mutex互斥信号量锁住的不是一个变量,而是阻塞住一段程序。如果对一个mutex变量testlock, 执行了第一次pthread_mutex_lock(testlock)之后,在unlock(testlock)之前的这段时间内,如果有其他线程也执行到了pthread_mutex_lock(testlock),这个线程就会阻塞住,直到之前的线程unlock之后才能执行,由此,实现同步,也就达到保护临界区资源的目的。
#include<stdio.h>
#include<pthread.h>

static pthread_mutex_t testlock;
pthread_t test_thread;

void *test()
{
pthread_mutex_lock(&testlock);
printf("thread Test() \n");
pthread_mutex_unlock(&testlock);
}

int main()
{
pthread_mutex_init(&testlock, NULL);
pthread_mutex_lock(&testlock); 

printf("Main lock \n");

pthread_create(&test_thread, NULL, test, NULL);
sleep(1); //更加明显的观察到是否执行了创建线程的互斥锁
printf("Main unlock \n");
pthread_mutex_unlock(&testlock); 

sleep(1);

pthread_join(test_thread,NULL); 
pthread_mutex_destroy(&testlock); 
return 0;
}

make
gcc -D_REENTRANT -lpthread -o test test.c

结果:
Main lock 
Main unlock 
thread Test()

二、条件变量
这里主要说说 pthread_cond_wait()的用法,在下面有说明。
条件变量是利用线程间共享的全局变量进行同步的一种机制,主要包括两个动作:个线程等待"条件变量的条件成立"而挂起;另一个线程使"条件成立"(给出条件成立信号)。为了防止竞争,条件变量的使用总是和一个互斥锁结合在一起。   
    
1.   创建和注销   

条件变量和互斥锁一样,都有静态动态两种创建方式,静态方式使用PTHREAD_COND_INITIALIZER常量,如下:     
pthread_cond_t   cond=PTHREAD_COND_INITIALIZER     

动态方式调用pthread_cond_init()函数,API定义如下:     
int   pthread_cond_init(pthread_cond_t   *cond,   pthread_condattr_t   *cond_attr)     
    
尽管POSIX标准中为条件变量定义了属性,但在LinuxThreads中没有实现,因此cond_attr值通常为NULL,且被忽略。   

注销一个条件变量需要调用pthread_cond_destroy(),只有在没有线程在该条件变量上等待的时候才能注销这个条件变量,否则返回EBUSY。因为Linux实现的条件变量没有分配什么资源,所以注销动作只包括检查是否有等待线程。API定义如下:     
int   pthread_cond_destroy(pthread_cond_t   *cond)     

2.   等待和激发   

int   pthread_cond_wait(pthread_cond_t   *cond,   pthread_mutex_t   *mutex)   
int   pthread_cond_timedwait(pthread_cond_t   *cond,   pthread_mutex_t   *mutex,   const   struct   timespec   *abstime)     



等待条件有两种方式:无条件等待pthread_cond_wait()和计时等待pthread_cond_timedwait(),其中计时等待方式如果在给定时刻前条件没有满足,则返回ETIMEOUT,结束等待,其中abstime以与time()系统调用相同意义的绝对时间形式出现,0表示格林尼治时间1970年1月1日0时0分0秒。   

无论哪种等待方式,都必须和一个互斥锁配合,以防止多个线程同时请求pthread_cond_wait()(或pthread_cond_timedwait(),下同)的竞争条件(Race   Condition)。mutex互斥锁必须是普通锁(PTHREAD_MUTEX_TIMED_NP)或者适应锁(PTHREAD_MUTEX_ADAPTIVE_NP),且在调用pthread_cond_wait()前必须由本线程加锁(pthread_mutex_lock()),而在更新条件等待队列以前,mutex保持锁定状态,并在线程挂起进入等待前解锁。在条件满足从而离开pthread_cond_wait()之前,mutex将被重新加锁,以与进入pthread_cond_wait()前的加锁动作对应。   执行pthread_cond_wait()时自动解锁互斥量(如同执行了 pthread_unlock_mutex),并等待条件变量触发。这时线程挂起,不占用 CPU 时间,直到条件变量被触发。

因此,全过程可以描述为:

(1)pthread_mutex_lock()上锁,

(2)pthread_cond_wait()等待,等待过程分解为为:解锁--条件满足--加锁

(3)pthread_mutex_unlock()解锁。   
激发条件有两种形式,pthread_cond_signal()激活一个等待该条件的线程,存在多个等待线程时按入队顺序激活其中一个;而pthread_cond_broadcast()则激活所有等待线程。 两者 如果没有等待的线程,则什么也不做。

下面一位童鞋问的问题解释了上面的说明:

当pthread_cond_t调用pthread_cond_wait进入等待状态时,pthread_mutex_t互斥信号无效了.

示例代码如下:

//多线程同步--条件锁(相当与windows的事件)测试

//要先让pthread_cond_wait进入等待信号状态,才能调用pthread_cond_signal发送信号,才有效.

//不能让pthread_cond_signal在pthread_cond_wait前面执行

#include <stdio.h>

#include<pthread.h> //多线程所用头文件

#include <semaphore.h> //信号量使用头文件

pthread_cond_t g_cond /*=PTHREAD_MUTEX_INITIALIZER*/; //申明条锁,并用宏进行初始化

pthread_mutex_t g_mutex ;

//线程执行函数

void threadFun1(void)

{

int i;

pthread_mutex_lock(&g_mutex); //1

pthread_cond_wait(&g_cond,&g_mutex); //如g_cond无信号,则阻塞

for( i = 0;i < 2; i++ ){

printf("thread threadFun1.\n");

sleep(1);

}

pthread_cond_signal(&g_cond);

pthread_mutex_unlock(&g_mutex);

}

int main(void)

{

pthread_t id1; //线程的标识符

pthread_t id2;

pthread_cond_init(&g_cond,NULL); //也可以程序里面初始化

pthread_mutex_init(&g_mutex,NULL); //互斥变量初始化

int i,ret;

ret = pthread_create(&id1,NULL,(void *)threadFun1, NULL);

if ( ret!=0 ) { //不为0说明线程创建失败

printf ("Create pthread1 error!\n");

exit (1);

}

sleep(5); //等待子线程先开始

pthread_mutex_lock(&g_mutex); //2

pthread_cond_signal(&g_cond); //给个开始信号,注意这里要先等子线程进入等待状态在发信号,否则无效

pthread_mutex_unlock(&g_mutex);

pthread_join(id1,NULL);

pthread_cond_destroy(&g_cond); //释放

pthread_mutex_destroy(&g_mutex); //释放

return 0;

}

大家请看红颜色的1和2.

明明是1先锁了互斥变量,但代码执行到2还是一样可以锁定.

为什么会这样呢????/

pthread_cond_wait()什么情况才会接锁,继续跑下去啊...现在来看一段典型的应用:看注释即可。

问题解释:当程序进入pthread_cond_wait等待后,将会把g_mutex进行解锁,当离开pthread_cond_wait之前,g_mutex会重新加锁。所以在main中的g_mutex会被加锁。 呵呵。。。

现在来看一段典型的应用:看注释即可。

#include <pthread.h>    
#include <unistd.h>    

static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;    
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;    

struct node {    
int n_number;    
struct node *n_next;    
} *head = NULL;    

/*[thread_func]*/    
static void cleanup_handler(void *arg)    
{    
printf("Cleanup handler of second thread.\n");    
free(arg);    
(void)pthread_mutex_unlock(&mtx);    
}    

static void *thread_func(void *arg)    
{    
struct node *p = NULL;    

pthread_cleanup_push(cleanup_handler, p);    
while (1) {    
pthread_mutex_lock(&mtx);           //这个mutex主要是用来保证pthread_cond_wait的并发性   
while (head == NULL)   {               //这个while要特别说明一下,单个pthread_cond_wait功能很完善,为何这里要有一个while (head == NULL)呢?因为pthread_cond_wait里的线程可能会被意外唤醒,如果这个时候head != NULL,则不是我们想要的情况。这个时候,应该让线程继续进入pthread_cond_wait   
pthread_cond_wait(&cond, &mtx);         // pthread_cond_wait会先解除之前的pthread_mutex_lock锁定的mtx,然后阻塞在等待对列里休眠,直到再次被唤醒(大多数情况下是等待的条件成立而被唤醒,唤醒后,该进程会先锁定先pthread_mutex_lock(&mtx);,再读取资源, 用这个流程是比较清楚的/*block-->unlock-->wait() return-->lock*/
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/errno.h>
#include <sys/types.h>
#include <signal.h>
#include <pthread.h>

#define    min(a,b)    ((a) < (b) ? (a) : (b))
#define    max(a,b)    ((a) > (b) ? (a) : (b))

#define    MAXNITEMS         1000000
#define    MAXNTHREADS            100

int        nitems;            /* read-only by producer and consumer */
struct {
pthread_mutex_t    mutex;
int    buff[MAXNITEMS];
int    nput;
int    nval;
} shared = { PTHREAD_MUTEX_INITIALIZER };

void    *produce(void *), *consume(void *);

/* include main */
int
main(int  argc , char **argv)
{
int            i, nthreads, count[MAXNTHREADS];
pthread_t    tid_produce[MAXNTHREADS], tid_consume;

if ( argc  != 3) {
printf("usage: prodcons3 <#items> <#threads>\n");
return -1;
}

nitems = min(atoi(argv[1]), MAXNITEMS);
nthreads = min(atoi(argv[2]), MAXNTHREADS);

/* 4create all producers and one consumer */

for (i = 0; i < nthreads; i++) {
count[i] = 0;
pthread_create(&tid_produce[i], NULL, produce, &count[i]);
}
pthread_create(&tid_consume, NULL, consume, NULL);

/* 4wait for all producers and the consumer */
for (i = 0; i < nthreads; i++) {
pthread_join(tid_produce[i], NULL);
printf("count[%d] = %d\n", i, count[i]);    
}
pthread_join(tid_consume, NULL);

exit(0);
}
/* end main */

void *
produce(void *arg)
{
for ( ; ; ) {
pthread_mutex_lock(&shared.mutex);
if (shared.nput >= nitems) {
pthread_mutex_unlock(&shared.mutex);
return(NULL);        /* array is full, we're done */
}
shared.buff[shared.nput] = shared.nval;
shared.nput++;
shared.nval++;
pthread_mutex_unlock(&shared.mutex);
*((int *) arg) += 1;
}
}

/* include consume */
void
consume_wait(int i)
{
for ( ; ; ) {
pthread_mutex_lock(&shared.mutex);
if (i < shared.nput) {
pthread_mutex_unlock(&shared.mutex);
return;            /* an item is ready */
}
pthread_mutex_unlock(&shared.mutex);
}
}

void *
consume(void *arg)
{
int        i;

for (i = 0; i < nitems; i++) {
consume_wait(i);
if (shared.buff[i] != i)
printf("buff[%d] = %d\n", i, shared.buff[i]);
}
return(NULL);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值