Reputation: 43
I'd like to have an object in C++ that does an asynchronous task in the background, but can still be requested to be freed by code using it without breaking things.
Let's say I have an object like this:
class MyObj {
std::thread* asyncTask;
bool result;
public:
MyObj() {
asyncTask = new std::thread([this](){
result = doSomething();
});
};
bool isResult() {
return result;
};
}
How would you go about making sure that the object can still be freed without terminating the process(due to thread still joinable/running at time of destruction)? I've thought about something involving delaying the destructor with a thread running counter, but that doesn't seem like the right solution. Part of the complexity is that the thread needs to normally access elements of the class, so it can't just detach either.
Upvotes: 0
Views: 953
Reputation: 275200
The only way to do this in general is to create a new process to handle the task (expensive, lots of marshalling and busywork), or have the thread cooperate.
A thread that cooperates regularly checks if it should abort. When it detects it should abort, it does so. It has to do this even when it is blocking on some resource.
For simple tasks, this is simple. For general tasks, next to impossible.
C++ compilers basically assume the threads get to act single threaded unless you go and explicitly synchronize operations. This permits certain important optimizations. The cost is that the state of a C++ thread need not make any sense at any point; so killing it or suspending it externally cannot be made safe (without cooperation).
In short, write your doSomething
with cooperation and abort in mind.
Upvotes: 1