一、互斥锁(mutex)
锁机制是同一时刻只允许一个线程执行一个关键部分的代码。
1 . 初始化锁
int pthread_mutex_init(pthread_mutex_t *mutex,const pthread_mutex_attr_t *mutexattr);
其中参数 mutexattr 用于指定锁的属性(见下),如果为NULL则使用缺省属性。
互斥锁的属性在创建锁的时候指定,在LinuxThreads实现中仅有一个锁类型属性,不同的锁类型在试图对一个已经被锁定的互斥锁加锁时表现不同。当前有四个值可供选择:
(1)PTHREAD_MUTEX_TIMED_NP,这是缺省值,也就是普通锁。当一个线程加锁以后,其余请求锁的线程将形成一个等待队列,并在解锁后按优先级获得锁。这种锁策略保证了资源分配的公平性。
(2)PTHREAD_MUTEX_RECURSIVE_NP,嵌套锁,允许同一个线程对同一个锁成功获得多次,并通过多次unlock解锁。如果是不同线程请求,则在加锁线程解锁时重新竞争。
(3)PTHREAD_MUTEX_ERRORCHECK_NP,检错锁,如果同一个线程请求同一个锁,则返回EDEADLK,否则与PTHREAD_MUTEX_TIMED_NP类型动作相同。这样就保证当不允许多次加锁时不会出现最简单情况下的死锁。
(4)PTHREAD_MUTEX_ADAPTIVE_NP,适应锁,动作最简单的锁类型,仅等待解锁后重新竞争。
2 . 阻塞加锁
int pthread_mutex_lock(pthread_mutex *mutex);
3 . 非阻塞加锁
int pthread_mutex_trylock( pthread_mutex_t *mutex);
该函数语义与 pthread_mutex_lock() 类似,不同的是在锁已经被占据时返回 EBUSY 而不是挂起等待。
4 . 解锁(要求锁是lock状态,并且由加锁线程解锁)
int pthread_mutex_unlock(pthread_mutex *mutex);
5 . 销毁锁(此时锁必需unlock状态,否则返回EBUSY)
int pthread_mutex_destroy(pthread_mutex *mutex);
示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int gn;
void* thread(void *arg)
{
printf("thread's ID is %d\n",pthread_self());
pthread_mutex_lock(&mutex);
gn = 12;
printf("Now gn = %d\n",gn);
pthread_mutex_unlock(&mutex);
return NULL;
}
int main()
{
pthread_t id;
printf("main thread's ID is %d\n",pthread_self());
gn = 3;
printf("In main func, gn = %d\n",gn);
if (!pthread_create(&id, NULL, thread, NULL)) {
printf("Create thread success!\n");
} else {
printf("Create thread failed!\n");
}
pthread_join(id, NULL);
pthread_mutex_destroy(&mutex);
return 0;
}
二、条件变量(condition_variable)
在C++11中,我们可以使用条件变量(condition_variable)实现多个线程间的同步操作;当条件不满足时,相关线程被一直阻塞,直到某种条件出现,这些线程才会被唤醒。
其主要成员函数如下:
条件变量是利用线程间共享的全局变量进行同步的一种机制,主要包括两个动作:
一个线程因等待"条件变量的条件成立"而挂起;
另外一个线程使"条件成立",给出信号,从而唤醒被等待的线程。
为了防止竞争,条件变量的使用总是和一个互斥锁结合在一起;通常情况下这个锁是std::mutex,并且管理这个锁 只能是 std::unique_lock<std::mutex> RAII模板类。
上面提到的两个步骤,分别是使用以下两个方法实现:
等待条件成立使用的是condition_variable类成员wait 、wait_for 或 wait_until。
给出信号使用的是condition_variable类成员notify_one或者notify_all函数。
细节说明
在条件变量中只能使用std::unique_lock<std::mutex>说明
unique_lock和lock_guard都是管理锁的辅助类工具,都是RAII风格;它们是在定义时获得锁,在析构时释放锁。它们的主要区别在于unique_lock锁机制更加灵活,可以再需要的时候进行lock或者unlock调用,不非得是析构或者构造时。它们的区别可以通过成员函数就可以一目了然。
wait/wait_for说明
线程的阻塞是通过成员函数wait()/wait_for()/wait_until()函数实现的。这里主要说明前面两个函数:
wait()成员函数
函数声明如下:
void wait( std::unique_lock<std::mutex>& lock );
//Predicate 谓词函数,可以普通函数或者lambda表达式
template< class Predicate >
void wait( std::unique_lock<std::mutex>& lock, Predicate pred );
wait 导致当前线程阻塞直至条件变量被通知,或虚假唤醒发生,可选地循环直至满足某谓词。
wait_for()成员函数
函数声明如下:
(1)
template< class Rep, class Period >
std::cv_status wait_for( std::unique_lock<std::mutex>& lock,
const std::chrono::duration<Rep, Period>& rel_time);
(2)
template< class Rep, class Period, class Predicate >
bool wait_for( std::unique_lock<std::mutex>& lock,
const std::chrono::duration<Rep, Period>& rel_time,
Predicate pred);
wait_for 导致当前线程阻塞直至条件变量被通知,或虚假唤醒发生,或者超时返回。
返回值说明:
(1)若经过 rel_time 所指定的关联时限则为 std::cv_status::timeout ,否则为 std::cv_status::no_timeout 。
(2)若经过 rel_time 时限后谓词 pred 仍求值为 false 则为 false ,否则为 true 。
以上两个类型的wait函数都在会阻塞时,自动释放锁权限,即调用unique_lock的成员函数unlock(),以便其他线程能有机会获得锁。这就是条件变量只能和unique_lock一起使用的原因,否则当前线程一直占有锁,线程被阻塞。
notify_all/notify_one
notify函数声明如下:
void notify_one() noexcept;
若任何线程在 *this 上等待,则调用 notify_one 会解阻塞(唤醒)等待线程之一。
void notify_all() noexcept;
若任何线程在 *this 上等待,则解阻塞(唤醒)全部等待线程。
虚假唤醒
在正常情况下,wait类型函数返回时要不是因为被唤醒,要不是因为超时才返回,但是在实际中发现,因此操作系统的原因,wait类型在不满足条件时,它也会返回,这就导致了虚假唤醒。因此,我们一般都是使用带有谓词参数的wait函数,因为这种(xxx, Predicate pred )类型的函数等价于:
while (!pred()) //while循环,解决了虚假唤醒的问题
{
wait(lock);
}
原因说明如下:
假设系统不存在虚假唤醒的时,代码形式如下:
if (不满足xxx条件)
{
//没有虚假唤醒,wait函数可以一直等待,直到被唤醒或者超时,没有问题。
//但实际中却存在虚假唤醒,导致假设不成立,wait不会继续等待,跳出if语句,
//提前执行其他代码,流程异常
wait();
}
//其他代码
...
正确的使用方式,使用while语句解决:
while (!(xxx条件) )
{
//虚假唤醒发生,由于while循环,再次检查条件是否满足,
//否则继续等待,解决虚假唤醒
wait();
}
//其他代码
....
条件变量使用
在这里,我们使用条件变量,解决生产者-消费者问题,该问题主要描述如下:
生产者-消费者问题,也称有限缓冲问题,是一个多进程/线程同步问题的经典案例。该问题描述了共享固定大小缓冲区的两个进程/线程——即所谓的“生产者”和“消费者”,在实际运行时会发生的问题。
生产者的主要作用是生成一定量的数据放到缓冲区中,然后重复此过程。与此同时,费者也在缓冲区消耗这些数据。该问题的关键就是要保证生产者不会在缓冲区满时加入数据,消费者也不会在缓冲区中空时消耗数据。
要解决该问题,就必须让生产者在缓冲区满时休眠(要么干脆就放弃数据),等到下次消费者消耗缓冲区中的数据的时候,生产者才能被唤醒,开始往缓冲区添加数据。
同样,也可以让消费者在缓冲区空时进入休眠,等到生产者往缓冲区添加数据之后,再唤醒消费者。
生产者-消费者代码如下:
std::mutex g_cvMutex;
std::condition_variable g_cv;
//缓存区
std::deque<int> g_data_deque;
//缓存区最大数目
const int MAX_NUM = 30;
//数据
int g_next_index = 0;
//生产者,消费者线程个数
const int PRODUCER_THREAD_NUM = 3;
const int CONSUMER_THREAD_NUM = 3;
void producer_thread(int thread_id)
{
while (true)
{
std::this_thread::sleep_for(std::chrono::milliseconds(500));
//加锁
std::unique_lock <std::mutex> lk(g_cvMutex);
//当队列未满时,继续添加数据
g_cv.wait(lk, [](){ return g_data_deque.size() <= MAX_NUM; });
g_next_index++;
g_data_deque.push_back(g_next_index);
std::cout << "producer_thread: " << thread_id << " producer data: " << g_next_index;
std::cout << " queue size: " << g_data_deque.size() << std::endl;
//唤醒其他线程
g_cv.notify_all();
//自动释放锁
}
}
void consumer_thread(int thread_id)
{
while (true)
{
std::this_thread::sleep_for(std::chrono::milliseconds(550));
//加锁
std::unique_lock <std::mutex> lk(g_cvMutex);
//检测条件是否达成
g_cv.wait( lk, [](){ return !g_data_deque.empty(); });
//互斥操作,消息数据
int data = g_data_deque.front();
g_data_deque.pop_front();
std::cout << "\tconsumer_thread: " << thread_id << " consumer data: ";
std::cout << data << " deque size: " << g_data_deque.size() << std::endl;
//唤醒其他线程
g_cv.notify_all();
//自动释放锁
}
}
int main()
{
std::thread arrRroducerThread[PRODUCER_THREAD_NUM];
std::thread arrConsumerThread[CONSUMER_THREAD_NUM];
for (int i = 0; i < PRODUCER_THREAD_NUM; i++)
{
arrRroducerThread[i] = std::thread(producer_thread, i);
}
for (int i = 0; i < CONSUMER_THREAD_NUM; i++)
{
arrConsumerThread[i] = std::thread(consumer_thread, i);
}
for (int i = 0; i < PRODUCER_THREAD_NUM; i++)
{
arrRroducerThread[i].join();
}
for (int i = 0; i < CONSUMER_THREAD_NUM; i++)
{
arrConsumerThread[i].join();
}
return 0;
}
运行结果:
说明:
1. pthread_cond_wait 自动解锁互斥量(如同执行了pthread_unlock_mutex),并等待条件变量触发。这时线程挂起,不占用CPU时间,直到条件变量被触发(变量为ture)。在调用 pthread_cond_wait之前,应用程序必须加锁互斥量。pthread_cond_wait函数返回前,自动重新对互斥量加锁(如同执行了pthread_lock_mutex)。
2. 互斥量的解锁和在条件变量上挂起都是自动进行的。因此,在条件变量被触发前,如果所有的线程都要对互斥量加锁,这种机制可保证在线程加锁互斥量和进入等待条件变量期间,条件变量不被触发。条件变量要和互斥量相联结,以避免出现条件竞争——个线程预备等待一个条件变量,当它在真正进入等待之前,另一个线程恰好触发了该条件(条件满足信号有可能在测试条件和调用pthread_cond_wait函数(block)之间被发出,从而造成无限制的等待)。
3. 条件变量函数不是异步信号安全的,不应当在信号处理程序中进行调用。特别要注意,如果在信号处理程序中调用 pthread_cond_signal 或 pthread_cond_boardcast 函数,可能导致调用线程死锁
相信很多人都会有这个疑问:为什么pthread_cond_wait需要的互斥锁不在函数内部定义,而要使用户定义的呢?现在没有时间研究 pthread_cond_wait 的源代码,带着这个问题对条件变量的用法做如下猜测,希望明白真相看过源代码的朋友不吝指正。
- pthread_cond_wait 和 pthread_cond_timewait 函数为什么需要互斥锁?因为:条件变量是线程同步的一种方法,这两个函数又是等待信号的函数,函数内部一定有须要同步保护的数据。
- 使用用户定义的互斥锁而不在函数内部定义的原因是:无法确定会有多少用户使用条件变量,所以每个互斥锁都须要动态定义,而且管理大量互斥锁的开销太大,使用用户定义的即灵活又方便,符合UNIX哲学的编程风格(随便推荐阅读《UNIX编程哲学》这本好书!)。
- 好了,说完了1和2,我们来自由猜测一下 pthread_cond_wait 函数的内部结构吧:
int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
{
if(没有条件信号)
{
(1)pthread_mutex_unlock (mutex); // 因为用户在函数外面已经加锁了(这是使用约定),但是在没有信号的情况下为了让其他线程也能等待cond,必须解锁。
(2) 阻塞当前线程,等待条件信号(当然应该是类似于中断触发的方式等待,而不是软件轮询的方式等待)... 有信号就继续执行后面。
(3) pthread_mutex_lock (mutex); // 因为用户在函数外面要解锁(这也是使用约定),所以要与1呼应加锁,保证用户感觉依然是自己加锁、自己解锁。
}
...
}
三、 信号量
如同进程一样,线程也可以通过信号量来实现通信,虽然是轻量级的。
线程使用的基本信号量函数有四个:
#include <semaphore.h>
- 1 . 初始化信号量
int sem_init (sem_t *sem , int pshared, unsigned int value);
- 参数:
sem - 指定要初始化的信号量;
pshared - 信号量 sem 的共享选项,linux只支持0,表示它是当前进程的局部信号量;
value - 信号量 sem 的初始值。
2 . 信号量值加1
给参数sem指定的信号量值加1。
int sem_post(sem_t *sem);
- 3 . 信号量值减1
给参数sem指定的信号量值减1。
int sem_wait(sem_t *sem);
- 如果sem所指的信号量的数值为0,函数将会等待直到有其它线程使它不再是0为止。
4 . 销毁信号量
销毁指定的信号量。
int sem_destroy(sem_t *sem);
- 示例代码:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <errno.h>
#define return_if_fail(p) if((p) == 0){printf ("[%s]:func error!\n", __func__);return;}
typedef struct _PrivInfo
{
sem_t s1;
sem_t s2;
time_t end_time;
}PrivInfo;
static void info_init (PrivInfo* prifo);
static void info_destroy (PrivInfo* prifo);
static void* pthread_func_1 (PrivInfo* prifo);
static void* pthread_func_2 (PrivInfo* prifo);
int main (int argc, char** argv)
{
pthread_t pt_1 = 0;
pthread_t pt_2 = 0;
int ret = 0;
PrivInfo* prifo = NULL;
prifo = (PrivInfo* )malloc (sizeof (PrivInfo));
if (prifo == NULL) {
printf ("[%s]: Failed to malloc priv.\n");
return -1;
}
info_init (prifo);
ret = pthread_create (&pt_1, NULL, (void*)pthread_func_1, prifo);
if (ret != 0) {
perror ("pthread_1_create:");
}
ret = pthread_create (&pt_2, NULL, (void*)pthread_func_2, prifo);
if (ret != 0) {
perror ("pthread_2_create:");
}
pthread_join (pt_1, NULL);
pthread_join (pt_2, NULL);
info_destroy (prifo);
return 0;
}
static void info_init (PrivInfo* prifo)
{
return_if_fail (prifo != NULL);
prifo->end_time = time(NULL) + 10;
sem_init (&prifo->s1, 0, 1);
sem_init (&prifo->s2, 0, 0);
return;
}
static void info_destroy (PrivInfo* prifo)
{
return_if_fail (prifo != NULL);
sem_destroy (&prifo->s1);
sem_destroy (&prifo->s2);
free (prifo);
prifo = NULL;
return;
}
static void* pthread_func_1 (PrivInfo* prifo)
{
return_if_fail (prifo != NULL);
while (time(NULL) < prifo->end_time)
{
sem_wait (&prifo->s2);
printf ("pthread1: pthread1 get the lock.\n");
sem_post (&prifo->s1);
printf ("pthread1: pthread1 unlock\n");
sleep (1);
}
return;
}
static void* pthread_func_2 (PrivInfo* prifo)
{
return_if_fail (prifo != NULL);
while (time (NULL) < prifo->end_time)
{
sem_wait (&prifo->s1);
printf ("pthread2: pthread2 get the unlock.\n");
sem_post (&prifo->s2);
printf ("pthread2: pthread2 unlock.\n");
sleep (1);
}
return;
}
四 读写锁
4.1 注意事项
- 1.如果一个线程用读锁锁定了临界区,那么其他线程也可以用读锁来进入临界区,这样就可以多个线程并行操作。但这个时候,如果再进行写锁加锁就会发生阻塞,写锁请求阻塞后,后面如果继续有读锁来请求,这些后来的读锁都会被阻塞!这样避免了读锁长期占用资源,防止写锁饥饿!
- 2.如果一个线程用写锁锁住了临界区,那么其他线程不管是读锁还是写锁都会发生阻塞!
4.2 常用接口
1. 初始化:
int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock, const pthread_rwlockattr_t *restrict attr);
- 读写加锁
int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_timedrdlock(pthread_rwlock_t *restrict rwlock, const struct timespec *restrict abs_timeout);
int pthread_rwlock_timedwrlock(pthread_rwlock_t *restrict rwlock, const struct timespec *restrict abs_timeout);
3.销毁锁
int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);
- 应用实例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
/* 初始化读写锁 */
pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
/* 全局资源 */
int global_num = 10;
void err_exit(const char *err_msg)
{
printf("error:%s\n", err_msg);
exit(1);
}
/* 读锁线程函数 */
void *thread_read_lock(void *arg)
{
char *pthr_name = (char *)arg;
while (1)
{
/* 读加锁 */
pthread_rwlock_rdlock(&rwlock);
printf("线程%s进入临界区,global_num = %d\n", pthr_name, global_num);
sleep(1);
printf("线程%s离开临界区...\n", pthr_name);
/* 读解锁 */
pthread_rwlock_unlock(&rwlock);
sleep(1);
}
return NULL;
}
/* 写锁线程函数 */
void *thread_write_lock(void *arg)
{
char *pthr_name = (char *)arg;
while (1)
{
/* 写加锁 */
pthread_rwlock_wrlock(&rwlock);
/* 写操作 */
global_num++;
printf("线程%s进入临界区,global_num = %d\n", pthr_name, global_num);
sleep(1);
printf("线程%s离开临界区...\n", pthr_name);
/* 写解锁 */
pthread_rwlock_unlock(&rwlock);
sleep(2);
}
return NULL;
}
int main(void)
{
pthread_t tid_read_1, tid_read_2, tid_write_1, tid_write_2;
/* 创建4个线程,2个读,2个写 */
if (pthread_create(&tid_read_1, NULL, thread_read_lock, "read_1") != 0)
err_exit("create tid_read_1");
if (pthread_create(&tid_read_2, NULL, thread_read_lock, "read_2") != 0)
err_exit("create tid_read_2");
if (pthread_create(&tid_write_1, NULL, thread_write_lock, "write_1") != 0)
err_exit("create tid_write_1");
if (pthread_create(&tid_write_2, NULL, thread_write_lock, "write_2") != 0)
err_exit("create tid_write_2");
/* 随便等待一个线程,防止main结束 */
if (pthread_join(tid_read_1, NULL) != 0)
err_exit("pthread_join()");
return 0;
}