I have a thread called mainloop
i.e.
int run_mainloop;
void* mainloop(void* param)
{
// local vars
// initialize local vars
while(run_mainloop)
{
// run mainloop
}
return 0;
}
The thread is kicked off from a function called client_open
, i.e.
int client_open()
{
run_mainloop = 1;
return pthread_create(&thread, NULL, mainloop, NULL);
}
However, in mainloop
if initializing local variables fails I need to inform client_open
right away of early exit.
pthread_join
is inappropriate as it will block and I can't have client_open
block.
If it was to wait a short time before returning that would be ok.
How could I do this in a nice way without using pthread_join which will block. I want to be able to get the return code.
Using pthread_tryjoin_np
would be incorrect: the new thread could be arbitrarily delayed between pthread_create
return, and the new thread actually executing initialization code.
If you pthread_tryjoin_np
during that delay, the join will fail and you will decide that everything is "a-ok", when in fact it isn't.
What you want is a condition: client_open
will await on it, and the mainloop
will signal it (upon being done with initialization).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With