如何实现多线程异步操作
How to implement a multi-threaded asynchronous operation?
以下是我当前的方法:
// Somewhere in a UI class
// Called when a button called "Start" clicked
MyWindow::OnStartClicked(Event &sender)
{
_thread = new boost::thread(boost::bind(&MyWindow::WorkToDo, this));
}
MyWindow::WorkToDo()
{
for(int i = 1; i < 10000000; i++)
{
int percentage = (int)((float)i / 100000000.f);
_progressBar->SetValue(percentage);
_statusText->SetText("Working... %d%%", percentage);
printf("Pretend to do something useful...n");
}
}
// Called on every frame
MyWindow::OnUpdate()
{
if(_thread != 0 && _thread->timed_join(boost::posix_time::seconds(0))
{
_progressBar->SetValue(100);
_statusText->SetText("Completed!");
delete _thread;
_thread = 0;
}
}
但我担心这是远远不安全的,因为我不断得到未处理的异常在程序执行结束。
我基本上想在不阻塞GUI部分的情况下,将繁重的任务分离到另一个线程中。
有很多方法可以做到这一点,很难确定。在Windows中,您通常会根据GUI操作启动线程,结果和/或进度会通过消息泵循环发布回GUI。您将声明或注册自定义窗口消息,并让工作线程的各种报告位置将它们发布到主窗口句柄或子窗口句柄设置中,以监控异步进度。
有很多方法可以做到这一点。以上只是一个描述,但对于中等程度的任务,我发现它通常可以解决问题。在这种情况下,您正在使用此处显示的代码。您直接设置并绕过消息循环(不是真的,但就您需要的而言),所以这应该可以工作。
如果您可以使用Boost或C++11,请尝试Boost/std::future和异步
相关文章:
- 为什么一个向量上的多线程操作很慢
- 在接收 SIGINT 操作时适当地关闭多线程 c++ 应用程序
- C++多线程操作比单线程慢
- 使用多线程处理的异步请求
- 发生哪些线程异步操作
- 如何实现多线程异步操作
- 多线程文件保存操作
- C++REST SDK:异步任务与C++11多线程
- 数组中的多线程写入操作
- 特征多线程操作
- 多线程队列原子操作
- OpenGL CL多线程互操作
- QML是否与多线程/异步调用兼容
- c++处理Linux多线程程序中的按键操作
- 提振.Asio复合操作在单线程和多线程进程
- 多线程套接字操作与进度条更新
- 两个或多个std::线程如何操作同一个函数
- 多线程和动态数组/矩阵操作
- boost::asio多线程异步接受,带有阻塞读/写服务器
- 多线程性能在执行几次操作后下降