互斥锁 pthread_mutex_t
互斥锁用来保证同一时间内只有一个线程在执行某段代码(临界区),最简单的用法:
pthread_mutex_t lock;
pthread_mutex_int(&lock, NULL);
...
pthread_mutex_lock(&lock);
...
pthread_mutex_unlock(&lock);
...
pthread_mutex_destroy(&lock);
1. 互斥锁创建和销毁
有两种方法创建互斥锁,静态方式和动态方式。
静态方式:
POSIX定义了一个宏PTHREAD_MUTEX_INITIALIZER来静态初始化互斥锁,方法如下:
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
动态方式:
采用pthread_mutex_init()函数来初始化互斥锁A:
int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr)
其中mutexattr用于指定互斥锁属性,如果为NULL则使用默认属性。
注销一个互斥锁,API定义如下:
int pthread_mutex_destroy(pthread_mutex_t *mutex)
2. 互斥锁属性
互斥锁的属性在创建锁的时候指定,在LinuxThreads实现中仅有一个锁类型属性,不同的锁类型在试图对一个已经被锁定的互斥锁加锁时表现不同。
当前(glibc2.2.3,linuxthreads0.9)有四个值可供选择:
PTHREAD_MUTEX_TIMED_NP,默认值,也就是普通锁。当一个线程加锁以后,其余请求锁的线程将形成一个等待队列,并在解锁后按优先级获得锁。这种锁策略保证了资源分配的公平性。
PTHREAD_MUTEX_RECURSIVE_NP,嵌套锁,允许同一个线程对同一个锁成功获得多次,并通过多次unlock解锁。如果是不同线程请求,则在加锁线程解锁时重新竞争。
PTHREAD_MUTEX_ERRORCHECK_NP,检错锁,如果同一个线程请求同一个锁,则返回EDEADLK,否则与PTHREAD_MUTEX_TIMED_NP类型动作相同。这样就保证当不允许多次加锁时不会出现最简单情况下的死锁。
PTHREAD_MUTEX_ADAPTIVE_NP,适应锁,动作最简单的锁类型,仅等待解锁后重新竞争。
A simple type of deadlock may occur when the same thread attempts to lock a
mutex twice in a row.The behavior in this case depends on what kind of mutex is
being used.Three kinds of mutexes exist:
Locking a fast mutex (the default kind) will cause a deadlock to occur.An
attempt to lock the mutex blocks until the mutex is unlocked. But because the
thread that locked the mutex is blocked on the same mutex, the lock cannot
ever be released.
Locking a recursive mutex does not cause a deadlock.A recursive mutex may
safely be locked many times by the same thread.The mutex remembers how
many times pthread_mutex_lock was called on it by the thread that holds the
lock; that thread must make the same number of calls to pthread_mutex_unlock
before the mutex is actually unlocked and another thread is allowed to lock it.
GNU/Linux will detect and flag a double lock on an error-checking mutex that
would otherwise cause a deadlock.The second consecutive call to
pthread_mutex_lock returns the failure code EDEADLK.
3. 锁操作
锁操作主要包括加锁 pthread_mutex_lock()、解锁pthread_mutex_unlock()和测试加锁pthread_mutex_trylock()三个,
不论哪种类型的锁,都不可能被两个不同的线程同时得到,而必须等待解锁。
对于普通锁和适应锁类型,解锁者可以是同进程内任何线程;
而检错锁则必须由加锁者解锁才有效,否则返回EPERM;
对于嵌套锁,文档和实现要求必须由加锁者解锁,但实验结果表明并没有这种限制,这个不同目前还没有得到解释。
在同一进程中的线程,如果加锁后没有解锁,则任何其他线程都无法再获得锁。
int pthread_mutex_lock(pthread_mutex_t *mutex)
int pthread_mutex_unlock(pthread_mutex_t *mutex)
int pthread_mutex_trylock(pthread_mutex_t *mutex)
pthread_mutex_trylock()语义与pthread_mutex_lock()类似,不同的是在锁已经被占据时返回EBUSY而不是挂起等待。
浙公网安备 33010602011771号