2 Star 5 Fork 1

beth/ConcurrencySample

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
condition_variable_1.cpp 1.35 KB
一键复制 编辑 原始数据 按行查看 历史
beth 提交于 2021-02-07 11:52 . Submit sample code.
/**
* @file condition_variable_1.cpp
* @brief ݵȴ
*/
#include <iostream>
#include <mutex>
#include <queue>
using namespace std;
bool more_data_to_prepare()
{
return false;
}
struct data_chunk
{
};
data_chunk prepare_data()
{
return data_chunk();
}
void process(data_chunk&)
{
}
bool is_last_chunk(data_chunk&)
{
return true;
}
mutex mut;
queue<data_chunk> data_queue;
condition_variable data_cond;
void data_preparation_thread()
{
while (more_data_to_prepare())
{
data_chunk const data = prepare_data();
lock_guard<mutex> lk(mut);
data_queue.push(data);
cout << "data_queue push data." << endl;
data_cond.notify_one();
//data_cond.notify_all();
}
}
void data_processing_thread()
{
while (true)
{
unique_lock<mutex> lk(mut);
data_cond.wait(
lk, [] { return !data_queue.empty(); });
//data_cond.wait_for(
// lk, 1000ms, [] { return !data_queue.empty(); });
//auto now = std::chrono::system_clock::now();
//data_cond.wait_until(
// lk, now + 1000ms, [] { return !data_queue.empty(); });
cout << "data_queue process data." << endl;
data_chunk data = data_queue.front();
data_queue.pop();
lk.unlock();
process(data);
if (is_last_chunk(data))
break;
}
}
int main()
{
//data_queue.push(data_chunk());
thread t1(data_preparation_thread);
thread t2(data_processing_thread);
t1.join();
t2.join();
return 0;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/bethjohanssen/concurrency-sample.git
git@gitee.com:bethjohanssen/concurrency-sample.git
bethjohanssen
concurrency-sample
ConcurrencySample
master

搜索帮助

0d507c66 1850385 C8b1a773 1850385