Reputation: 1
I am working on Ubuntu 12.04.2 LTS. I have a strange problem with pthread_kill()
. The following program ends after writing only "Create thread 0!"
to standard output. The program ends with exit status 138.
If I uncomment "usleep(1000);"
everything executes properly. Why would this happen?
#include <nslib.h>
void *testthread(void *arg);
int main() {
pthread_t tid[10];
int i;
for(i = 0; i < 10; ++i) {
printf("Create thread %d!\n", i);
Pthread_create(&tid[i], testthread, NULL);
//usleep(1000);
Pthread_kill(tid[i], SIGUSR1);
printf("Joining thread %d!\n", i);
Pthread_join(tid[i]);
printf("Joined %d!", i);
}
return 0;
}
void sighandlertest(int sig) {
printf("print\n");
pthread_exit();
//return NULL;
}
void* testthread(void *arg) {
struct sigaction saction;
memset(&saction, 0, sizeof(struct sigaction));
saction.sa_handler = &sighandlertest;
if(sigaction(SIGUSR1, &saction, NULL) != 0 ) {
fprintf(stderr, "Sigaction failed!\n");
}
printf("Starting while...\n");
while(true) {
}
return 0;
}
Upvotes: 0
Views: 438
Reputation: 70911
If the main thread does not sleep a bit before raising the SIGUSR1
, the signal handler for the thread created most propably had not been set up, so the default action for receiving the signal applies, which is ending the process.
Using sleep()
s to synchronise threads is not recommended as not guaranteed to be reliable. Use other mechanics here. A condition/mutex pair would be suitable.
Declare a global state variable int signalhandlersetup = 0
, protect access to it by a mutex, create the thread, make the main thread wait using pthread_cond_wait()
, let the created thread set up the signal handle for SIGUSR1
, set signalhandlersetup = 0
and then signal the condition the main thread is waiting on using pthread_signal_cond()
. Finally let the main thread call pthread_kill()
as by your posting.
Upvotes: 1