My application creates several threads with pthread_create() and then tries to verify their presence with pthread_kill(threadId, 0). Every once in a while the pthread_kill fails with “No such process”…
Could it be, I’m calling pthread_kill too early after pthread_create? I thought, the threadId returned by pthread_create() is valid right away, but it seems to not always be the case…
I do check the return value of pthread_create() itself — it is not failing… Here is the code-snippet:
if (pthread_create(&title->thread, NULL,
process_title, title)) {
ERR("Could not spawn thread for `%s': %m",
title->name);
continue;
}
if (pthread_kill(title->thread, 0)) {
ERR("Thread of %s could not be signaled.",
title->name);
continue;
}
And once in a while I get the message about a thread, that could not be signaled…
That’s really an implementation issue. The thread may exist or it may still be in a state of initialisation where
pthread_killwon’t be valid yet.If you really want to verify that the thread is up and running, put some form of inter-thread communication in the thread function itself, rather than relying on the underlying details.
This could be as simple as an array which the main thread initialises to something and the thread function sets it to something else as its first action. Something like (pseudo-code obviously):
From that code above, you actually use the
runningstate to control both when the main thread knows all other threads are doing something, and to shutdown threads as necessary.