Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect early exit from pthread_create without blocking for too long?

Tags:

c

linux

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.

like image 782
hookenz Avatar asked Jan 02 '12 22:01

hookenz


1 Answers

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).

like image 169
Employed Russian Avatar answered Oct 07 '22 05:10

Employed Russian