c++ - 如何在 C++ 中异步执行一个函数?

标签 c++ multithreading thread-safety pthreads threadpool

我现在正在为一个 C++ 队列管理程序工作。我添加了我的虚拟代码和序列图。 SomeClass::Handler中有很多Data数据。所以我必须将所有数据保存到我的队列中。 worker 必须操作数据以转换为 Command 实例。所以我想创建一个线程来从数据生成命令。但是我想将工作线程的数量限制为一个,以便命令生成进程的数量始终为一个。生成命令后,我想将此命令返回给 SomeClass。

我完全不知道如何实现这个设计。任何帮助将不胜感激。

编辑以获取更多规范。

  1. 如何限制工作线程的数量,而不是避免将数据插入队列?
  2. 如何从 woker 线程返回命令实例?

`

void MyClass::notify_new_data()
{
  // if there are no worker, I want to start new worker
  // But how?
}

// I want to limit the number of worker to one.
void MyClass::worker() {
  // busy loop, so should I add sleep_for(time) at the bottom of this func?
  while(queue.empty() == false) {
    MyData data;
    {
      lock_guard<std::mutex> lock(mtx);
      data = queue.pop();
    }
    // do heavy processing with data
    auto command = do_something_in_this thread();
    // how to pass this command to SomeClass!?
  }
}

// this class is called via aother thread.
void MyClass::push_data(MyData some_data) {
  {
    lock_guard<std::mutex> lock(mtx);
    queue.push(some_data);
  }
  notify_new_data();
}

void SomeClass::Handler(Data d) {
  my_class.push(data);
}

void SomeClass::OnReceivedCommand(Command cmd) {
  // receive command
}

enter image description here

最佳答案

问题不是很清楚。我假设:

  • 您需要一个单个工作线程来异步执行一些操作。

  • 您需要从另一个线程获取工作线程的计算结果。


How to restrict the number of worker thread, not avoiding pushing data to queue?

查看"thread pooling" .创建一个线程池,其中包含一个从线程安全队列读取的工作线程。这几乎就是您的 MyClass::worker() 正在做的事情。

// busy loop, so should I add sleep_for(time) at the bottom of this func?

您可以使用条件变量和锁定机制来防止忙等待,或者使用成熟的无锁队列实现,如moodycamel::ConcurrentQueue。 .

// how to pass this command to SomeClass!?

在线程之间传递数据的最干净和最安全的方式是使用 futures and promises . std::future page on cppreference是一个很好的起点。

// if there are no worker, I want to start new worker

我会在开始计算之前创建一个包含单个事件工作线程的线程池,这样您就不必检查工作线程是否可用。如果你做不到,一个std::atomic标志是否已创建 worker 就足够了。

关于c++ - 如何在 C++ 中异步执行一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37657548/

相关文章:

c++ - "static char __ = []() -> char"的含义

c++ - 如何调整 QTextEdit 以适合其内容

c - 分配 :what can "corrupt" allocated memory in Linux/Qt application (threads involved)?

java - 当所有线程都死了时停止应用程序

c++ - pthread Windows 事件等效问题

java - ConcurrentHashMap 的线程安全

c++ - Gtkmm 构建错误

objective-c - 此 View 动画概念的正确干净且线程安全的设计

ruby - 线程安全的 Ruby 解释器是什么意思?

python - 是否有 C++11 等同于 Python 的 @property 装饰器?