指定线程的std :: async模拟

Vla*_*hov 1 c++ qt multithreading asynchronous future

我需要处理几个对象,每个操作可能需要很长时间.

处理无法放在GUI(主)线程中,我在其中启动它.

我需要做的所有的一些对象在通信上的异步操作,类似的东西std::asyncstd::futureQtConcurrent::run()在我的主要框架(Qt的5),用QFuture等,但它不提供线程的选择.我总是需要在一个额外的线程中使用选定的对象(objects == devices),

因为:

  1. 我需要制作一个通用的解决方案,并且不希望每个类都是线程安全的
  2. 例如,即使为QSerialPort创建一个线程安全的容器,Qt中的串口也无法在多个线程中访问:

注意:串行端口始终以独占访问权限打开(即,没有其他进程或线程可以访问已打开的串行端口).

  1. 通常,与设备的通信包括发送命令和接收答案.我想在发送请求的地方准确处理每个答案,并且不想使用仅事件驱动的逻辑.

所以,我的问题.

如何实现该功能?

MyFuture<T> fut = myAsyncStart(func, &specificLiveThread);
Run Code Online (Sandbox Code Playgroud)

一个活动线程必须多次传递.

Ram*_*mes 5

让我回答没有引用Qt库,因为我不知道它的线程API.

在C++ 11标准库中,没有直接的方法来重用创建的线程.线程执行单个功能,只能加入或分离.但是,您可以使用生产者 - 消费者模式实现它.消费者线程需要执行std::function由生产者线程放置在队列中的任务(例如表示为对象).所以,如果我是正确的,你需要一个单线程的线程池.

我可以推荐我的C++ 14线程池实现作为任务队列.它不常用(但是!),但是它用单元测试覆盖并用线程消毒剂多次检查.文档很稀疏,但随时可以在github问题中提出任何问题!

库存储库:https://github.com/Ravirael/concurrentpp

而你的用例:

#include <task_queues.hpp>

int main() {
    // The single threaded task queue object - creates one additional thread.
    concurrent::n_threaded_fifo_task_queue queue(1);

    // Add tasks to queue, task is executed in created thread.
    std::future<int> future_result = queue.push_with_result([] { return 4; });

    // Blocks until task is completed.
    int result = future_result.get();

    // Executes task on the same thread as before.
    std::future<int> second_future_result = queue.push_with_result([] { return 4; });
}
Run Code Online (Sandbox Code Playgroud)