-
概念
-
mutex 互斥锁是一种简单的加锁的方法来控制对共享资源的访问
-
在同一时刻只能有一个线程掌握某个互斥上的锁,拥有上锁状态的线程能够对共享资源进行访问
-
若其他线程希望上锁一个已经被上了互斥锁的资源,则该线程挂起,直到上锁的线程释放互斥锁为止
-
-
互斥锁的操作步骤
-
互斥锁初始化:pthread_mutex_init
-
互斥锁上锁:pthread_mutex_lock
-
互斥锁解锁:pthread_mutex_unlock
-
消除互斥锁:pthread_mutex_destroy
-
-
互斥锁初始化
-
函数名:pthread_mutex_init
-
头文件:
#include <pthread.h>
-
函数原型:
int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutex_attr_t *mutexattr);
-
mutex:互斥锁
-
mutexattr:通常设置为 NULL
-
PTHREAD_MUTEX_INITIALIZER:创建快速互斥锁
-
PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP:创建递归互斥锁
-
PTHREAD_REEORCHECK_MUTEX_INITIALIZER_NP:创建检错互斥锁
-
-
-
-
互斥锁操作
-
头文件:
#include <pthread.h>
-
函数原型:
int pthread_mutex_lock(pthread_mutex_t *mutex); int pthread_mutex_unlock(pthread_mutex_t *mutex); int pthread_mutex_destroy(pthread_mutex_t *mutex);
-
mutex:互斥锁
-
返回值:执行成功返回 0,发送错误返回 -1
-
-
-
出现原因
pthread_mutex_t work_mutex; int i = 3; int j = 7;
// thread_A // thread_B pthread_lock() pthread_lock() { { i++; if(i == j) j--; do_something(); } } pthread_unlock(); pthread_unlock();
-
初始化条件变量
extern int pthread_cond_init(pthread_cond_t *cond, pthread_condattr_t *cond_attr);
-
销毁条件变量
extern int pthread_cond_destroy(pthread_cond_t *cond);
-
初始化条件变量举例
pthread_cond_t cv; pthread_condattr_t cattr; int ret; ret = pthread_cond_init(&cv, NULL); ret = pthread_cond_init(&cv, &cattr);
-
通知条件变量
extern int pthread_cond_signal(pthread_cond_t *cond);
-
等待条件变量
extern int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);
-
举例
-
基本原则:
-
如果某线程申请了读锁,其他线程可以再申请读锁,但不能申请写锁
-
如果某线程申请了写锁,其他线程不能申请读锁,也不能申请写锁
-
-
初始化读写锁
extern int pthread_rwlock_init(pthread_rwlock_t *rwlock, pthread_rwlockattr_t *attr);
-
注销读写锁
extern int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);
-
申请写锁
extern int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
-
申请读锁
extern int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
-
解锁
extern int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
- End -