使用通常称为 API 实现C++多个客户和生产者解决方案,这是否有效?

Implement a C++ multiple customer and producer solution with frequently called api, does this work?

本文关键字:解决方案 生产者 客户 有效 是否 C++ 实现 API      更新时间:2023-10-16
// 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的访问(如果需要),这样您就不会阻止使用者线程。

相关文章: