#include <iostream>
#include <list>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
// 环形链表
// 三个线程
// 一个插入数值
// 一个读取
// 调节插入、读取的频率, 取到的数值永远是最新的数据
const int max_size = 10;
std::priority_queue<int> data;
std::mutex lock;
std::condition_variable not_full;
std::condition_variable not_empty;
bool read_interupt = false;
void read_func()
{
while (!read_interupt)
{
std::unique_lock<std::mutex> uniqueLock(lock);
if (data.empty())
{
not_empty.wait(uniqueLock);
}
else
{
std::cout << "read current value: " << data.top() << std::endl;
data.pop();
not_full.notify_one();
}
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
}
bool write_interupt = false;
void write_func()
{
int count = 0;
while (!write_interupt)
{
std::unique_lock<std::mutex> uniqueLock(lock);
if (data.size() >= max_size)
{
count++;
not_full.wait(uniqueLock);
}
else
{
data.push(count);
std::cout << "write current value: " << count << std::endl;
count++;
not_empty.notify_one();
}
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
}
}
int main()
{
std::thread reader(read_func);
std::thread writer(write_func);
reader.join();
writer.join();
return 0;
}
文章评论