一、深入理解linux互斥锁(mutex)
锁机制,可以说是linux整个系统的精髓所在,linux内核都是围绕着同步在运转。在多进程和多线程编程中,锁起着极其重要的作用。我这里说的是互斥锁,其实是泛指linux中所有的锁机制。我在这里不讲如果创建锁,关于锁的创建,网上代码很多,我在这里就不多说了。我要谈一谈一个让所有刚刚接触锁机制的程序员都很困惑的问题:如何使用以及锁机制在程序中是如何运作的。
1、为什么要使用锁
这个就比较简单,linux里面,锁的种类很多,包括互斥锁,文件锁,读写锁······其实信号量说白了也是一种锁。使用锁的目的是达到同步的作用,使共享资源在同一时间内,只有能有一个进程或者线程对他进行操作。
2、linux是如何通过锁来实现对数据的保护和维护的
这个问题是我要将的重点。很多刚刚接触锁机制的程序员,都会犯这种错误。比如,此时有2个线程,分别是线程A,线程B。A和B共享了资源M。为了同步A和B,使得同一时刻,同意时刻,只有一个线程对M操作。于是,很自然的会在A中对M资源先lock,等到A对M操作完毕之后,然后做一个操作unlock。B中则因为A加了锁,B就直接操作M。这个时候,你会发现,B同样可以操作到M。这个是为什么呢?
我们利索当然的把检测锁的任务交给了操作系统,交给了内核。可以翻看APUE上对于所的讲解,其中一部分是这么写的:
This mutual-exclusion mechanism works only if we design our threads to follow the same data-access rules. The operating system doesn't serialize access to data for us. If we allow one thread to access a shared resource without first acquiring a lock, then inconsistencies can occur even though the rest of our threads do acquire the lock before attempting to access the shared resource.
这里This mutual-exclusion mechanism指的就是锁机制。说的很清楚,只有程序员设计线程的时候,都遵循同一种数据访问规则,锁机制才会起作用。操作系统不会为我们序列化数据访问,也就是说,操作系统不会为我们拟定任何数据访问顺序,到底是A在先还是B在先,操作系统不会为我们规定。如果我们允许一个线程在没有多的锁(lock)之前,就对共享数据进行访问操作,那么,即使我们其他的线程都在访问之前试图去先锁住资源(获取锁),同样会导致数据访问不一致,即多个线程同时在操作共享资源。
从上面文字可以看出,操作系统不会为我们去检查,此时是不是有线程已经把资源锁住了。为了使锁能够正常工作,为了保护共享资源,我们只有在设计线程的时候,所有线程都用同一种方法去访问共享数据,也就是访问数据之前,务必先获取锁,然后再操作,操作完之后要解锁(unlock)。操作系统提供锁机制,就是提供了一种所有程序员都必须遵循的规范。而不是说我们锁住资源,其他线程访问共享资源的时候,让操作系统去为我们检查数据是否有其他的线程在操作。
版权申明:
转载文章请注明原文出处http://blog.csdn.net/feiyinzilgd/archive/2010/08/16/5816653.aspx
二、 pthread_mutex 家庭成员:
1.int pthread_mutex_init
(pthread_mutex_t *mutex , pthread_mutexattr_t * attr );
Description
The pthread_mutex_init function initializes the given mutex with the given attributes. Ifattr is null, then the default attributes are used.
2. int pthread_mutex_destroy
(pthread_mutex_t *mutex );
Description
The pthread_mutex_destroy function destroys the given mutex. If the mutex is already destroyed, thenerrno is set to EINVAL. If the mutex is locked, then errno is set to EBUSY.
3.int pthread_mutex_lock
(pthread_mutex_t *mutex );
Description
The pthread_mutex_lock function locks the given mutex. If the mutex is already locked, then the calling thread blocks until the thread that currently holds the mutex unlocks it.
4.int pthread_mutex_trylock
(pthread_mutex_t *mutex );
Description
The pthread_mutex_trylock function tries to lock the given mutex. If the mutex is already locked, the function returns without waiting for the mutex to be unlocked.
Returns
The pthread_mutex_trylock function returns zero if the call is successful, otherwise it setserrno to EINVAL and returns -1.
5.int pthread_mutex_unlock
(pthread_mutex_t *mutex );
Description
The pthread_mutex_unlock function unlocks the given mutex.
三、成员作用
1. 互斥锁的初始化和销毁
.初始化有两种初始化方式:
a. 对于静态分配的互斥锁一半用宏赋值的方式初始化
eg:static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
b. 对于动态分配的互斥锁(如调用malloc)或分配在共享内存中,则必须调用
pthread_mutex_init(pthread_mutex*mutex, pthread_mutexattr_t *mutexattr)函数来进行初始化。
动态分配释放例子:
pthread_mutex_init(*mutex ,*attr);
pthread_mutex_destory(*mutex)
pthread_mutexattr_init(*attr)
pthread_mutexattr_destory(*attr)动态分配的代码:
pthread_mutex_t
lock=(pthread_mutex_t *)malloc(sizeof(szieof(pthread_mutex_t)));
pthread_mutex_init(lock ,NULL);
. 互斥锁摧毁
pthread_mutex_destory(lock);
free(lock);
销毁一个互斥锁即意味着释放它所占用的资源,且要求锁当前处于开放状态。由于在Linux中,互斥锁并不占用任何资源,因此LinuxThreads中的 pthread_mutex_destroy()除了检查锁状态以外(锁定状态则返回EBUSY)没有其他动作。
2. 互斥锁上锁、尝试上锁和解锁
要对公共变量进行上锁来进行保护,必须最少要上两个锁以上,换句话说就得调用pthread_mutex_lock()函数两次以上,否则,只是上一个锁会达不到相应的效果。尝试上锁pthread_mutex_trylock()和pthread_mutex_lock()的区别是:后者会阻塞等待另外一个锁被解锁;前者尝试去加锁,如果不成功就返回非0,如果成功返回0,不会产生阻塞。
每次上锁之后,一定要解锁,否则会造成程序一直在阻塞状态。
四、互斥锁函数详解
互斥锁,是一种信号量,常用来防止两个进程或线程在同一时刻访问相同的共享资源。可以保证以下三点:
原子性:把一个互斥量锁定为一个原子操作,这意味着操作系统(或pthread函数库)保证了如果一个线程锁定了一个互斥量,没有其他线程在同一时间可以成功锁定这个互斥量。
唯一性:如果一个线程锁定了一个互斥量,在它解除锁定之前,没有其他线程可以锁定这个互斥量。
非繁忙等待:如果一个线程已经锁定了一个互斥量,第二个线程又试图去锁定这个互斥量,则第二个线程将被挂起(不占用任何cpu资源),直到第一个线程解除对这个互斥量的锁定为止,第二个线程则被唤醒并继续执行,同时锁定这个互斥量。
从以上三点,我们看出可以用互斥量来保证对变量(关键的代码段)的排他性访问。
2.函数说明:
需要的头文件:pthread.h
1)初始化互斥锁
函数原型:int pthread_mutex_init(pthread_mutex_t *mp, const pthread_mutexattr_t *mattr)
参数说明:mp 互斥锁地址 mattr 属性 通常默认 null
初始化互斥锁之前,必须将其所在的内存清零。
如果互斥锁已初始化,则它会处于未锁定状态。互斥锁可以位于进程之间共享的内存中或者某个进程的专用内存中。
2)锁定互斥锁
函数原型:
int pthread_mutex_lock(pthread_mutex_t *mutex); #include <pthread.h> pthread_mutex_t mutex; int ret; ret = pthread_ mutex_lock(&mp); /* acquire the mutex */
函数说明:
当 pthread_mutex_lock() 返回时,该互斥锁已被锁定。调用线程是该互斥锁的属主。如果该互斥锁已被另一个线程锁定和拥有,则调用线程将阻塞,直到该互斥锁变为可用为止。
如果互斥锁类型为 PTHREAD_MUTEX_NORMAL,则不提供死锁检测。尝试重新锁定互斥锁会导致死锁。如果某个线程尝试解除锁定的互斥锁不是由该线程锁定或未锁定,则将产生不确定的行为。
如果互斥锁类型为 PTHREAD_MUTEX_ERRORCHECK,则会提供错误检查。如果某个线程尝试重新锁定的互斥锁已经由该线程锁定,则将返回错误。如果某个线程尝试解除锁定的互斥锁不是由该线程锁定或者未锁定,则将返回错误。
如果互斥锁类型为 PTHREAD_MUTEX_RECURSIVE,则该互斥锁会保留锁定计数这一概念。线程首次成功获取互斥锁时,锁定计数会设置为 1。线程每重新锁定该互斥锁一次,锁定计数就增加 1。线程每解除锁定该互斥锁一次,锁定计数就减小 1。 锁定计数达到 0 时,该互斥锁即可供其他线程获取。如果某个线程尝试解除锁定的互斥锁不是由该线程锁定或者未锁定,则将返回错误。
如果互斥锁类型是 PTHREAD_MUTEX_DEFAULT,则尝试以递归方式锁定该互斥锁将产生不确定的行为。对于不是由调用线程锁定的互斥锁,如果尝试解除对它的锁定,则会产生不确定的行为。如果尝试解除锁定尚未锁定的互斥锁,则会产生不确定的行为。
返回值:
pthread_mutex_lock() 在成功完成之后会返回零。其他任何返回值都表示出现了错误。如果出现以下任一情况,该函数将失败并返回对应的值。
EAGAIN:由于已超出了互斥锁递归锁定的最大次数,因此无法获取该互斥锁。
EDEADLK:当前线程已经拥有互斥锁。
3)解除锁定互斥锁
函数原型:
int pthread_mutex_unlock(pthread_mutex_t *mutex); #include <pthread.h> pthread_mutex_t mutex; int ret; ret = pthread_mutex_unlock(&mutex); /* release the mutex */
函数说明:pthread_mutex_unlock() 可释放 mutex 引用的互斥锁对象。互斥锁的释放方式取决于互斥锁的类型属性。如果调用 pthread_mutex_unlock() 时有多个线程被 mutex 对象阻塞,则互斥锁变为可用时调度策略可确定获取该互斥锁的线程。对于 PTHREAD_MUTEX_RECURSIVE 类型的互斥锁,当计数达到零并且调用线程不再对该互斥锁进行任何锁定时,该互斥锁将变为可用。
返回值:pthread_mutex_unlock() 在成功完成之后会返回零。
其他任何返回值都表示出现了错误。如果出现以下情况,该函数将失败并返回对应的值。
EPERM :当前线程不拥有互斥锁。
4)使用非阻塞互斥锁锁定
函数原型:
int pthread_mutex_trylock(pthread_mutex_t *mutex); #include <pthread.h> pthread_mutex_t mutex; int ret; ret = pthread_mutex_trylock(&mutex); /* try to lock the mutex */
函数说明:pthread_mutex_trylock() 是 pthread_mutex_lock() 的非阻塞版本。如果 mutex 所引用的互斥对象当前被任何线程(包括当前线程)锁定,则将立即返回该调用。否则,该互斥锁将处于锁定状态,调用线程是其属主。
返回值:pthread_mutex_trylock() 在成功完成之后会返回零。其他任何返回值都表示出现了错误。如果出现以下任一情况,该函数将失败并返回对应的值。
EBUSY :
由于 mutex 所指向的互斥锁已锁定,因此无法获取该互斥锁。
EAGAIN:描述:
由于已超出了 mutex 的递归锁定最大次数,因此无法获取该互斥锁。
5)销毁互斥锁
函数原型:
int pthread_mutex_destroy(pthread_mutex_t *mp); #include <pthread.h> pthread_mutex_t mp; int ret; ret = pthread_mutex_destroy(&mp); /* mutex is destroyed */请注意,没有释放用来存储互斥锁的空间。
返回值:
pthread_mutex_destroy() 在成功完成之后会返回零。其他任何返回值都表示出现了错误。如果出现以下任一情况,该函数将失败并返回对应的值。
EINVAL: mp 指定的值不会引用已初始化的互斥锁对象。
3.例子:
互斥锁用来保证一段时间内只有一个线程在执行一段代码。必要性显而易见:假设各个线程向同一个文件顺序写入数据,最后得到的结果一定是灾难性的。
我们先看下面一段代码。这是一个读/写程序,它们公用一个缓冲区,并且我们假定一个缓冲区只能保存一条信息。即缓冲区只有两个状态:有信息或没有信息。
void reader_function ( void );
void writer_function ( void );
char buffer;
int buffer_has_item=0;
pthread_mutex_t mutex;
struct timespec delay;
void main ( void ){
pthread_t reader;
/* 定义延迟时间*/
delay.tv_sec = 2;
delay.tv_nec = 0;
/* 用默认属性初始化一个互斥锁对象*/
pthread_mutex_init (&mutex,NULL);
pthread_create(&reader, pthread_attr_default, (void *)&reader_function), NULL);
writer_function( );
}
void writer_function (void){
while(1){
/* 锁定互斥锁*/
pthread_mutex_lock (&mutex);
if (buffer_has_item==0){
buffer=make_new_item( );
buffer_has_item=1;
}
/* 打开互斥锁*/
pthread_mutex_unlock(&mutex);
pthread_delay_np(&delay);
}
}
void reader_function(void){
while(1){
pthread_mutex_lock(&mutex);
if(buffer_has_item==1){
consume_item(buffer);
buffer_has_item=0;
}
pthread_mutex_unlock(&mutex);
pthread_delay_np(&delay);
}
}
程序说明:
这里声明了互斥锁变量mutex,结构pthread_mutex_t为不公开的数据类型,其中包含一个系统分配的属性对象。函数pthread_mutex_init用来生成一个互斥锁。NULL参数表明使用默认属性。如果需要声明特定属性的互斥锁,须调用函数pthread_mutexattr_init。函数pthread_mutexattr_setpshared和函数pthread_mutexattr_settype用来设置互斥锁属性。前一个函数设置属性pshared,它有两个取值,PTHREAD_PROCESS_PRIVATE和PTHREAD_PROCESS_SHARED。前者用来不同进程中的线程同步,后者用于同步本进程的不同线程。
在上面的例子中,我们使用的是默认属性PTHREAD_PROCESS_ PRIVATE。后者用来设置互斥锁类型,可选的类型有PTHREAD_MUTEX_NORMAL、PTHREAD_MUTEX_ERRORCHECK、PTHREAD_MUTEX_RECURSIVE和PTHREAD _MUTEX_DEFAULT。它们分别定义了不同的上锁、解锁机制,一般情况下,选用最后一个默认属性。
pthread_mutex_lock声明开始用互斥锁上锁,此后的代码直至调用pthread_mutex_unlock为止,均被上锁,即同一时间只能被一个线程调用执行。当一个线程执行到pthread_mutex_lock处时,如果该锁此时被另一个线程使用,那此线程被阻塞,即程序将等待到另一个线程释放此互斥锁。在上面的例子中,我们使用了pthread_delay_np函数,让线程睡眠一段时间,就是为了防止一个线程始终占据此函数。
4.饥饿和死锁的情形
当一个互斥量已经被别的线程锁定后,另一个线程调用pthread_mutex_lock()函数去锁定它时,会挂起自己的线程等待这个互斥量被解锁。可能出现以下两种情况:
“饥饿状态”:这个互斥量一直没有被解锁,等待锁定它的线程将一直被挂着,即它请求某个资源,但永远得不到它。用户必须在程序中努力避免这种“饥饿”状态出现。Pthread函数库不会自动处理这种情况。
“死锁”:一组线程中的所有线程都在等待被同组中另外一些线程占用的资源,这时,所有线程都因等待互斥量而被挂起,它们中的任何一个都不可能恢复运行,程序无法继续运行下去。这时就产生了死锁。Pthread函数库可以跟踪这种情形,最后一个线程试图调用pthread_mutex_lock()时会失败,并返回类型为EDEADLK的错误。
五、代码讲解:
代码说明1:互斥锁基本应用
#include<stdio.h>
#include<pthread.h>
#include"unistd.h"
pthread_mutex_tmutex = PTHREAD_MUTEX_INITIALIZER;
intcount = 0;
void*consume( void *arg)
{
while(1 )
{
pthread_mutex_lock(&mutex );
printf("************************consumebegin lock\n");
printf("************************consumed%d\n",count );
sleep(2);
count++;
printf("************************consumed%d\n",count);
printf("************************consumeover lock\n");
pthread_mutex_unlock(&mutex );
printf("************************I'mout of pthread_mutex\n");
sleep(1);
}
}
void* produce( void * arg )
{
while(1 )
{
pthread_mutex_lock(&mutex );
printf("productbegin lock\n");
printf("Produced %d\n", count );
printf("productover lock\n");
pthread_mutex_unlock(&mutex );
printf("I'mout of pthread_mutex\n");
sleep(1);
}
}
intmain( void )
{
pthread_tthread1,thread2;
pthread_create(&thread1, NULL, &produce, NULL );
pthread_create(&thread2, NULL, &consume, NULL );
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
return0;
}
结果显示:
[elbort@elborttest1]$ gcc -Wall -lpthread -o test test.c
[elbort@elborttest1]$ ./test
productbegin lock
Produced0
productover lock
I'mout of pthread_mutex
************************consumebegin lock
************************consumed0
/*中间等待了2秒但是product线程没有执行|*/
************************consumed1
************************consumeover lock
************************I'mout of pthread_mutex
productbegin lock
Produced1
productover lock
I'mout of pthread_mutex
************************consumebegin lock
************************consumed1
************************consumed2
************************consumeover lock
************************I'mout of pthread_mutex
productbegin lock
Produced2
productover lock
I'mout of pthread_mutex
/************************************************************************/
代码说明2:单一调用互斥锁没效果
void*consume( void *arg)
{
while(1 )
{
pthread_mutex_lock(&mutex );
printf("************************consumebegin lock\n");
printf("************************consumed%d\n",count );
sleep(2);
count++;
printf("************************consumed%d\n",count);
printf("************************consumeover lock\n");
pthread_mutex_unlock(&mutex );
printf("************************I'mout of pthread_mutex\n");
sleep(1);
}
}
void* produce( void * arg )
{
while(1 )
{
count=count+5;
printf("Produced %d\n", count );
sleep(1);
}
}
intmain( void )
{
pthread_tthread1,thread2;
pthread_create(&thread1, NULL, &produce, NULL );
pthread_create(&thread2, NULL, &consume, NULL );
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
return0;
}
~
~
结果说明:
[elbort@elborttest1]$ ./test
Produced5
************************consumebegin lock
************************consumed5
Produced10 //线程comsume被中断,conut的值被线程product修改
************************consumed11
************************consumeover lock
************************I'mout of pthread_mutex
/********************************************************/
代码说明3:pthread_mutex_trylock作用
intcount = 0;
void*consume( void *arg)
{
while(1 )
{
pthread_mutex_lock(&mutex );
printf("************************consumebegin lock\n");
printf("************************consumed%d\n",count );
sleep(2);
count++;
printf("************************consumed%d\n",count);
printf("************************consumeover lock\n");
pthread_mutex_unlock(&mutex );
printf("************************I'mout of pthread_mutex\n");
sleep(1);
}
}
void* produce( void * arg )
{
while(1 )
{
if(pthread_mutex_trylock(&mutex ) == 0)
{
printf("productbegin lock\n");
count++;
printf("Produced %d\n", count );
printf("productover lock\n");
pthread_mutex_unlock(&mutex );
printf("I'mout of pthread_mutex\n");
sleep(1);
}
else
{
printf("Ihave try!But i can lock the mutex!\n");
sleep(1);
}
}
}
intmain( void )
{
pthread_tthread1,thread2;
pthread_create(&thread1, NULL, &produce, NULL );
pthread_create(&thread2, NULL, &consume, NULL );
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
return0;
}
结果显示:
[elbort@elborttest1]$ ./test
************************consumebegin lock
************************consumed0
Ihave try!But i can lock the mutex!
Ihave try!But i can lock the mutex!
************************consumed1
************************consumeover lock
************************I'mout of pthread_mutex
productbegin lock
Produced2
productover lock
I'mout of pthread_mutex
************************consumebegin lock
************************consumed2
Ihave try!But i can lock the mutex!
Ihave try!But i can lock the mutex!
************************consumed3
************************consumeover lock
************************I'mout of pthread_mutex
productbegin lock
Produced4
productover lock
I'mout of pthread_mutex