问题1:在使用notify_*的前面部分或者后面部分需要使用unlock进行解锁吗?
我在网上看有的代码没有使用unlock,如下:
#include <Windows.h>
#include <cstdlib>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
static const int bufSize = 10; // Item buffer size.
static const int ProNum = 20; // How many items we plan to produce.
struct resource {
int buf[bufSize]; // 产品缓冲区, 配合 read_pos 和 write_pos 模型环形队列.
size_t read_pos; // 消费者读取产品位置.
size_t write_pos; // 生产者写入产品位置.
std::mutex mtx; // 互斥量,保护产品缓冲区
std::condition_variable not_full; // 条件变量, 指示产品缓冲区不为满.
std::condition_variable not_empty; // 条件变量, 指示产品缓冲区不为空.
} instance; // 产品库全局变量, 生产者和消费者操作该变量.
typedef struct resource resource;
void Producer(resource* ir, int item)
{
std::unique_lock<std::mutex> lock(ir->mtx);
while (((ir->write_pos + 1) % bufSize)
&