Hey, I’m creating a Thread that send a request to an external API with uploading and retrieving some files, I wondered how to know when the Thread is finished:
Look into using std::future or juce::WaitableEvent. These both allow you to suspend a thread until it is woken-up by another one.
std::async might be a better option for your threading needs here–it will allow you to write things a lot more succinctly.
std::future<int> f = std::async([]() // async returns a future automatically
{
// do stuff here
return 4;
});
int i = f.get(); // .get() waits for the std::future to resolve and returns the value
Also, look out for the memory leak on the first line of your code; use std::unique_ptr here instead of raw pointers.
f.get() blocks the thread until the task is done if i remember right. This is the same as a synchronous call in my opinion.
Some kind of await that waits without blocking the thread would be required.
I think Kunz is right, waiting for the thread to finish is not the right approach here (I was misunderstanding what you were trying to do when I suggested std::future). Using MessageManager::callAsync is probably the easiest approach here. If it were me, I would still use std::async instead of juce::Thread here, just because the setup is much easier–you don’t need to define a class, and can just use a simple lambda.
Be careful though because this line is unsafe:
MessageManager::callAsync([this, result]() {
if (onFinishedCallback)
onFinishedCallback(result);
});
You’re capturing this and then running it at a later date, but it’s possible that this has been deleted since then. To solve this, you’ll probably need to use some shared_ptr or weak_ptr.
This problem is solved when using a juce::ThreadPool instance on the class that has the callback function. It will wait until the thread/job is finished when destruction happens.