c++ - 异步函数调用,带有检查进度的方法

标签 c++ multithreading asynchronous

我需要帮助在 C++ 中实现异步函数调用。我是 C++ 多线程的新手。

应该有两个功能:一个是在另一个线程中开始工作,另一个是检查进度以及工作是否已经完成。

我尝试使用来自该站点上不同答案的一些代码,但它不起作用。

int __stdcall Test::asyncStartWork()
{
    asyncReady = false;
    std::thread workThread = std::thread(&Test::doWork, this);
    return 0;
}

int __stdcall Test::asyncGetProgress()
{
    if (asyncReady = true)
    {
        workThread.join();
        return 100;
    }    
    else
    {
        return asyncProgress;
    }
}

int __stdcall Test::doWork()
{
   //do work and write progress to asyncProgress

   //at the end
   asyncReady = true
}

调用 asyncStartWork 时出现以下错误:

enter image description here

最佳答案

在方法 Test::asyncStartWork() 中,您定义了一个局部变量 workThread,它隐藏了您的类成员。

因此在 asyncGetProgress() 中,当调用 workThread.join() 时,您正在为不代表线程的线程对象调用它(参见 here ) .

这导致 std::system_error 被抛出,错误条件为 no_such_process。如果您的程序没有捕获异常,这将导致进程中止。

尝试删除 asyncStartWork() 中的 std::thread 部分,例如

int __stdcall Test::asyncStartWork()
{
    asyncReady = false;
    workThread = std::thread(&Test::doWork, this);
    return 0;
}

此外,__stdcall 似乎没有必要。

关于c++ - 异步函数调用,带有检查进度的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36133276/

相关文章:

java - 多线程异常和锁

c# - 多个 Web 请求的最佳多线程方法

android - 如何使用一个异步任务从 android 更新两个不同的 Mysql 表?

C++: map ,键的前一项

c++ - 在 C++ 中出现此错误, "no match for ' operator>>' in ' std :cin. std

c++ - 模板成员函数无法自动推断类型

javascript - $.post 不工作(任何地方)!为什么?

c++ - 为什么 `this`等于0x0,导致我的程序崩溃?

java - 线程因 sleep 而暂停后会发生什么?

python - Tornado 非阻塞请求