Attention: http://www.linuxidc.com/Linux/2012-03/57249p7.htm
1. 互斥锁:
说白了就是可以是线程之间或者进程之间互斥访问共享资源!
函数:
pthread_mutex_init 初始化一个互斥量
pthread_mutex_lock 给一个互斥量加锁
pthread_mutex_trylock 在锁已经被占据时返回EBUSY而不是挂起
pthread_mutex_unlock 解锁
加锁后只有加锁权限的线程或者进程才可以进行操作,其他的要
访问共享资源就只能是wait等待... ...
关于初始化问题有两种方法:
1.直接静态设置pthread_mutex_t量为PTHREAD_MUTEX_INITIALIZER
2.可以动态设置使用函数pthread_mutex_inti( ... )
2. 初始化和回收互斥锁
#include<pthread.h>
>>>>>:
intpthread_mutex_init( pthread_mutex_t * mutex, const
pthread_mutexattr_t * attr );
参数:mutex 互斥量
attr 互斥锁属性
若成功则返回0,否则返回错误编号。
>>>>>:
intpthread_mutex_destroy( pthread_mutex_t * mutex);
参数:mutex 互斥量
若成功则返回0,否则返回错误编号。
3. 对互斥量加减锁:
#include<pthread.h>
intpthread_mutex_lock(pthread_mutex_t*mutex); //!> 加锁
intpthread_mutex_trylock(pthread_mutex_t*mutex); //!>
//在锁已经被占据时返回EBUSY而不是挂起等
intpthread_mutex_unlock(pthread_mutex_t*mutex); //!> 去锁
若成功则返回0,否则返回错误编号。
4. 上面的测试代码我们知道对于初始化时的属性都是设置为NULL的,
也就是pthread_mutex_init( &g_mutex, NULL);
但是很多时候是不可以的NULL的,所以下面就是解决mutex属性
pthread_mutexattr_t
#include<pthread.h>
intpthread_mutexattr_init( pthread_mutexattr_t * attr );
//!> 初始化属性
intpthread_mutexattr_destroy( pthread_mutexattr_t * attr );
//!> 回收
若成功返回0,若失败返回错误编号。
注意: