c++ - std::async 指定线程的模拟

标签 c++ multithreading qt asynchronous future

我需要处理多个对象,其中每个操作可能需要很长时间。

无法将处理放在我启动它的 GUI(主)线程中。

我需要与一些对象进行所有通信 on asynchronous operations , 类似于 std::asyncstd::futureQtConcurrent::run()在我的主要框架( Qt 5 )中,使用 QFuture等,但它不提供线程选择。我需要始终只在一个额外的线程中处理选定的对象(对象 == 设备),

因为:

  1. 我需要做一个通用的解决方案,不想让每个类都是线程安全的
  2. 例如,甚至如果为QSerialPort 创建一个线程安全的容器,Serial port in Qt不能在多个线程中访问:

Note: The serial port is always opened with exclusive access (that is, no other process or thread can access an already opened serial port).

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

所以,我的问题。

功能如何实现?

MyFuture<T> fut = myAsyncStart(func, &specificLiveThread);

一个活线程可以多次传递是必要的。

最佳答案

让我在不引用 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; });
}

关于c++ - std::async 指定线程的模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49507620/

相关文章:

c++ - 如何将二进制表示字节转储为十进制字符串?

C++ const 指针 - 无法解释的行为

Java线程在没有通知的情况下死亡

c# - 我应该为包含 Thread 的类实现 IDisposable

c++ - qt designer如何选择一个QStackedWidget页面的多个 child ?

java - Android 中的 OpenCV 旋转(去偏斜)- C++ 到 Java 的转换

c++ - 您是否打算从违反契约(Contract)中恢复过来?

c++ - Matlab绘图功能与Qt C++程序

java - 在这个例子中使用ConcurrentMap.replace有什么意义

Qt::它可以做多小?