使用std::packaged_task在线程间传递任务


/*
 * @Description: 使用std::packaged_task在GUI线程上运行代码
 * @Version: 1.0
 * @Author: hanhy
 */

#include <deque>
#include <future>
#include <mutex>
#include <thread>
#include <utility> //这里有move函数

std::mutex m;
std::deque<std::packaged_task<void()>> tasks;

bool gui_shutdown_message_received();
void get_and_process_gui_message();

void gui_thread() {// 1
  while (!gui_shutdown_message_received()) { // 2
    get_and_process_gui_message();  // 3
    std::packaged_task<void()> task;
    {
      std::lock_guard<std::mutex> lk(m);
      if (tasks.empty())           //4
        continue;
      // move将对象的状态或对象转移到另一个对象,原来那个对象就为空了。
      task = std::move(tasks.front());  //5
      tasks.pop_front();
    }
    task();            // 6
  }
}

std::thread gui_bg_thread(gui_thread);

template <typename Func> std::future<void> post_task_for_gui_thread(Func f) {
  std::packaged_task<void()> task(f);  // 7
  std::future<void> res = task.get_future();  // 8
  std::lock_guard<std::mutex> lk(m);
  tasks.push_back(std::move(task));  // 9
  return res;
}

std::packaged_task<> 类模板参数为函数签名,像int(std::string&,double*)表示接受对std::string的非const引用和指向double的指针,并返回int的函数。
返回值做为异步结果,存储在由get_future()获取的std::future中。因此可以将任务封装在std::packaged_task中,并在别的地方获取结果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

海洋2416

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值