基础概念
在介绍生产者-消费者模式之前,首先讲讲线程与进程的区别,以及互斥锁和条件变量、信号量
- 线程:进程执行流的最小单元
- 进程:操作系统执行流的最小单元
- 进程与线程的区别:每个进程都有独立的内存空间,因此多进程将耗费大量系统资源,而线程只有栈区是独立的,堆区和数据都是共享的。如下图所示
线程销毁:在c中使用pthread_detach()来引导线程销毁,一般服务端不使用pthread_join(),因为该函数会一直阻塞等待线程终止,而对于服务端来说是不能这样阻塞的。
互斥锁:主要用于线程安全,可以通过创建互斥锁,并将需要保护的临界区使用lock和unlock围住,当前线程在执行临界区代码时,其它线程会进入阻塞状态。防止同一变量被多个线程同时操作,导致混乱
条件变量:和互斥锁配合使用,主要用于消费者-生产者模式,实现线程同步
信号量: 定义两个信号量,并将初值分别初始化为0,1,也可以实现线程同步. 调用一次sem_wait()对应的信号量就减1,当信号量值已经为0了,如果又运行到sem_wait()就会阻塞,直到sem_post()运行,给该信号量值+1。
生产者-消费者问题
我们直接通过代码来进行分析
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| #include <iostream> #include <thread> #include <mutex> #include <condition_variable> #include <queue> #include <chrono>
std::queue<int> buffer;
const unsigned int BUFFER_SIZE = 10;
std::mutex mtx; std::condition_variable cv_producer; std::condition_variable cv_consumer;
void producer(int id) { int product = 0; while (true) { std::unique_lock<std::mutex> lock(mtx);
cv_producer.wait(lock, []() { return buffer.size() < BUFFER_SIZE; });
product++; buffer.push(product); std::cout << "Producer " << id << " produced: " << product << std::endl;
cv_consumer.notify_all();
lock.unlock(); std::this_thread::sleep_for(std::chrono::milliseconds(100)); } }
void consumer(int id) { while (true) { std::unique_lock<std::mutex> lock(mtx);
cv_consumer.wait(lock, []() { return !buffer.empty(); });
int consumed_product = buffer.front(); buffer.pop(); std::cout << "Consumer " << id << " consumed: " << consumed_product << std::endl;
cv_producer.notify_all();
lock.unlock(); std::this_thread::sleep_for(std::chrono::milliseconds(150)); } }
int main() { std::thread producer1(producer, 1); std::thread producer2(producer, 2); std::thread consumer1(consumer, 1); std::thread consumer2(consumer, 2);
producer1.join(); producer2.join(); consumer1.join(); consumer2.join();
return 0; }
|
上述代码的输出结果为
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| Producer 1 produced: 1 Producer 2 produced: 1 Consumer 1 consumed: 1 Consumer 2 consumed: 1 Producer 2 produced: 2 Producer 1 produced: 2 Consumer 1 consumed: 2 Consumer 2 consumed: 2 Producer 1 produced: 3 Producer 2 produced: 3 Consumer 1 consumed: 3 Consumer 2 consumed: 3 Producer 1 produced: 4 Producer 2 produced: 4 .....
|
假设消费者先获得锁:
消费者调用std::unique_lock<std::mutex> lock(mtx)获取锁
消费者执行
1
| cv_consumer.wait(lock, []() { return !buffer.empty(); })
|
- 由于
buffer.empty()为真,!buffer.empty()为假
- 消费者会释放锁并进入等待状态
此时锁被释放,生产者可以获取锁
生产者获得锁:
生产者调用std::unique_lock<std::mutex> lock(mtx)获取锁
生产者执行
1
| cv_producer.wait(lock, []() { return buffer.size() < BUFFER_SIZE; })
|
- 由于
buffer.size() < BUFFER_SIZE为真(缓冲区为空)
- 生产者不阻塞,继续执行
生产者放入数据:buffer.push(product)
生产者调用
1
| cv_consumer.notify_all()
|
- 关键点:这里仅发送通知,不会立即唤醒消费者线程
- 消费者线程仍在等待状态,只有当锁被释放后才会被唤醒
生产者通过lock.unlock()释放锁
这时消费者线程才会被唤醒并尝试重新获取锁
消费者被唤醒:
消费者获取锁
消费者重新检查条件
消费者从缓冲区取出数据并处理
消费者调用cv_producer.notify_all()通知生产者
消费者通过lock.unlock()释放锁
在这里我们使用了互斥锁保护了临界区,如下所示,在多线程运行的情况下,通过互斥锁保证了buffer中数据是正常的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| std::unique_lock<std::mutex> lock(mtx);
cv_producer.wait(lock, []() { return buffer.size() < BUFFER_SIZE; });
product++; buffer.push(product); std::cout << "Producer " << id << " produced: " << product << std::endl;
cv_consumer.notify_all();
lock.unlock();
std::unique_lock<std::mutex> lock(mtx);
cv_consumer.wait(lock, []() { return !buffer.empty(); });
int consumed_product = buffer.front(); buffer.pop(); std::cout << "Consumer " << id << " consumed: " << consumed_product << std::endl;
cv_producer.notify_all();
lock.unlock();
|
此外,我们还需要注意以下几点:
条件变量通知后不会立即执行:当线程A调用notify_all()时,线程B不会立即从等待状态恢复执行。线程B只有在线程A释放锁后才有机会获取锁并检查条件。
条件变量始终与锁配合使用:
wait()操作会自动释放锁
- 被通知唤醒后,线程会重新尝试获取锁
- 获取锁成功后,会再次检查条件
条件变量防止虚假唤醒:wait()函数的谓词参数(lambda函数)用于防止虚假唤醒。即使线程被错误地唤醒,它也会检查条件是否真的满足。
通知只是发信号,不会立即触发执行:通知只是告诉等待的线程”可能满足条件了”,被通知的线程仍然需要:
- 等待当前持有锁的线程释放锁
- 获取锁
- 重新检查条件是否满足
线程的栈区是独立的,所以两个生产者输出的produced才会是独立的,而其它全局区数据是多线程共享的
补充:信号量实现线程同步
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
static sem_t sem_one; static sem_t sem_two; int main(int argc, char *argv[]) { pthread_t id_t1, id_t2; sem_init(&sem_one, 0, 0); sem_init(&sem_two, 0, 1); pthread_create(&id_t1, NULL, read, NULL); pthread_create(&id_t2, NULL, accu, NULL); pthread_join(id_t1, NULL); pthread_join(id_t2, NULL); sem_destroy(&sem_one); sem_destroy(&sem_two); return 0; }
void *read(void *arg) { for (int i = 0; i < 5; i++) { fputs("Input num: ", stdout); sem_wait(&sem_two); scanf("%d", num); sem_post(&sem_one); } }
void *accu(void *arg) { for (int i = 0; i < 5; i++) { sem_wait(&sem_one); num += 1; sem_post(&sem_two); } }
|