- 读写锁,互斥锁并不是任何时候都能阻塞线程运行
1. 假设有线程操作如下:
a. 链表头节点Node *head = NULL
b. wile(head == NULL)
{
//当链表为空时,希望线程阻塞
//等待链表中有节点时再执行下面代码
}
//链表中不为空时执行代码段
...
- 条件变量
1. 条件变量并不是锁,本质是一组函数,用来阻塞线程
2. 条件变量 + 互斥锁 = 线程同步
a. 互斥锁:保护一块共享数据
b. 条件变量:引起阻塞
3. 动作:
a. 阻塞线程
b. 唤醒一个阻塞的线程
4. 条件变量类型:
pthread_cond_t cond
5. 初始化条件变量:
pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);
6. 销毁条件变量:
pthread_cond_destroy(pthread_cond_t *cond);
7. 阻塞等待
pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex);
作用:
a. 阻塞线程
b. 将已经上锁的mutex解锁,这样可以让其他线程操作保护的共享资源
c. 当线程解除阻塞时,会对mutex进行加锁状态,保持之前的状态一致
8. 限时等待一个条件变量:
pthread_cond_timedwait(pthread_cond_t *restrict cond,
pthread_mutex_t *restrict mutex,
const struct timespec *restrict abstime);
9. 唤醒阻塞线程:
a. 至少唤醒一个:
pthread_cond_signal(pthread_cond_t *cond); //如果阻塞了10个,则至少唤醒1个
b. 唤醒全部:
pthread_cond_broadcast(pthread_cond_t *cond); //如果阻塞了10个,则唤醒10个