【发布时间】:2021-12-22 01:47:04
【问题描述】:
操作系统窗口。我想在绘制之前创建一个后缓冲区。我想使用 boost::asio::thread_pool 来提高速度。如果我的“输入数据”(任务)被更新,我需要停止创建后台缓冲区。 我写了 Test_CreateAndCancel 函数来简化测试。
class Task
{
public:
virtual void operator()
{
std::cout << "Task started " << std::endl;
DoSomeWork();
std::cout << "Task in progress" << std::endl;
for (int i = 0; i < 15; ++i)
boost::this_thread::sleep_for(boost::chrono::milliseconds(1000));
std::cout << "Task ended" << std::endl;
}
};
using TaskPtr = std::shared_ptr<Task>;
void Test_CreateAndCancel(std::vector<TaskPtr> &tasks)
{
//start back-buffer creating
boost::asio::thread_pool _thread_pool(4);
for (auto task : tasks)
{
boost::asio::post(thread_pool, [task] {
task->operator()();
});
}
// simulate cancel
thread_pool.stop(); // wait untill all threads are finished?
}
向量任务有 4 个项目。 结果是:4“任务开始”“任务进行中”“任务结束”
我正在考虑在 task::operator() 中添加自定义 IsCanceled() 检查。
还有其他方法可以取消我的任务吗? 如何实现取消逻辑?
如有任何建议,我将不胜感激 谢谢
【问题讨论】:
-
比较boost.org/doc/libs/1_77_0/doc/html/thread/…,或Concurrency In Action 的第9 章(Manning 在线免费)
标签: boost threadpool