使用通常称为 API 实现C++多个客户和生产者解决方案,这是否有效?
Implement a C++ multiple customer and producer solution with frequently called api, does this work?
// a known api to get ids to buffer
void get_ids(int nums, int * buffer) {};
调用get_ids将导致 1 秒,我想实现一个客户和生产者模型,必须调用客户并且可以在每秒 1/5000 内返回结果。有更好的解决方案吗?
queue<int> Q;
int * buffer;
mutex mu;
condition_variable cond;
void producer() {
while (1) {
if (Q.size() < 5000) {
unique_lock<mutex> locker(mu);
get_ids(5000, buffer);
for (int i = 0; i < 5000; ++i) {
Q.push(buffer[i]);
}
locker.unlock();
cond.notify_all();
}
}
}
int customer() {
int id;
unique_lock<mutex> locker(mu);
cond.wait(locker, [](){return !Q.empty();});
id = Q.top();
Q.pop();
locker.unlock();
return id;
}
此解决方案是否有效?还是会导致任何潜在问题?有没有更好的解决方案?
当您从队列中读取数据时,您无需将其与get_ids同步。
因此,如果您只有一个生产者(和多个消费者),那么生产者代码中的这种修改应该没问题(只需在get_ids后移动锁):
void producer() {
while (1) {
if (Q.size() < 5000) {
get_ids(5000, buffer);
unique_lock<mutex> locker(mu);
for (int i = 0; i < 5000; ++i) {
Q.push(buffer[i]);
}
locker.unlock();
cond.notify_all();
}
}
}
如果您有多个创建者,则需要单独的互斥锁来保护对get_ids的访问(如果需要),这样您就不会阻止使用者线程。
相关文章:
- 运行同一解决方案的另一个项目的项目
- Project Euler问题4的错误解决方案
- 计算每个节点的树高,帮助我解释这个代码解决方案
- C++:Application.cpp中抛出了未解析的外部符号(解决方案在问题的末尾,供未来的读者参考)
- visual c++,如何获取解决方案目录中的代码
- 有没有办法在远程设备上打开和编辑visual Studio 2017解决方案
- C++Matching Brackets 2解决方案不起作用
- 在 ubuntu3 上C++ goto 定义有什么解决方案吗16.04?
- 在 leetcode 上提交解决方案时出现堆栈缓冲区溢出错误
- 我的固定时间步长与增量时间和插值的解决方案是错误的吗?
- 无法在问题解决方案中执行输出逻辑
- 最大的回文产品 - 程序未运行,编写解决方案但无法理解问题
- 从预序遍历构造 bst 的 c++ 和 python 解决方案之间的区别
- 在一个解决方案中针对第三方静态库 (Creo) 的不同版本(版本)进行构建
- 如何巧妙地编写两个函数——一个用于检查是否存在解决方案,另一个用于获取所有解决方案
- 使用 Git 处理 C++ Visual Studio 2019 解决方案的外部依赖项源代码管理的最佳方法是什么?
- N-queen问题:无法弄清楚为什么我的解决方案不起作用
- 从排序数组中删除重复项,具有不同代码方式的相同解决方案具有不同的输出
- 使用通常称为 API 实现C++多个客户和生产者解决方案,这是否有效?
- 如何将并发解决方案应用于类似生产者-消费者的情况