如何实现多线程异步操作

How to implement a multi-threaded asynchronous operation?

本文关键字:多线程 异步操作 实现 何实现      更新时间:2023-10-16

以下是我当前的方法:

// 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和异步