首页 > 解决方案 > 使用经常调用的 api 实现 C++ 多客户和生产者解决方案,这行得通吗?

问题描述

// 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;
}

这个解决方案有效吗?或者会导致任何潜在的问题?有没有更好的解决方案?

标签: c++multithreadingproducer-consumer

解决方案


当您从队列中读取数据时,您不需要将其与 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 的访问(如果需要),这样您就不会阻塞消费者线程。


推荐阅读