rkgghz rkgghz - 1 month ago 9
C++ Question

Asynchronous function call, with a method to check progress

I need help to implement an asynchonous funtion call in C++. I am new to multithreading in C++.

There sould be two funtions: one to get the work started in another thread and one to check progress and if work has been finished.

I tried it with some code from different answers on this site, but it doesn't work.

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
}


When calling asyncStartWork I get the following error:

enter image description here

Answer

In method Test::asyncStartWork(), you are defining a local variable workThread which is hiding your class member.

So in asyncGetProgress(), when calling workThread.join(), you're calling it for a thread object which does not represent a thread (see here).

This results in a std::system_error being thrown with error condition no_such_process. If your program is not catching exceptions, this would result in the process aborting.

Try removing the std::thread part in asyncStartWork(), e.g.

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

Also, the __stdcall's seem unnecessary.