I have this question:
- How can I kill a thread (maybe with
pthread_cancel()
) from another thread?
Here is the sample code.
I need that when I press 1, the other thread gets killed. (I must force the kill from one thread without putting a pthread_exit()
in the other.)
pthread_t THR_INPUT, THR_QUEUE;
void *thr_in(void *null) {
int opt;
while(1){
printf("1. Kill the other thread\n");
scanf("%d", &opt);
switch (opt)
{
case 1:
pthread_cancel(THR_QUEUE);
pthread_exit(NULL);
default:
printf("ATTENZIONE: Scelta %i non corretta. Riprovare.\n",opt);
}
}
}
void *thr_qu(int reparto) {
while(1){
sleep(2);
printf("I'm alive!");
}
}
int main(int argc, const char * argv[]){
void *result;
printf("-------start-------\nMenu:\n");
pthread_mutex_init(&mutex, NULL);
pthread_create(&THR_INPUT, NULL, thr_in, NULL);
pthread_create(&THR_QUEUE, NULL, thr_qu(reparto), NULL);
pthread_join(THR_INPUT, &result);
pthread_join(THR_QUEUE, &result);
printf("---end---\n");
exit(EXIT_SUCCESS);
}
I think about a solution but I don't know how clean it is; just do this:
int main(int argc, const char * argv[]){
void *result;
sem = semget(SEM_KEY, 0, 0);
pthread_mutex_init(&mutex, NULL);
int pid=getpid();
pid=fork();
if(!pid){
printf("-------START-------\nMenu:\n");
pthread_create(&THR_INPUT, NULL, thr_in, NULL);
pthread_create(&THR_QUEUE, NULL, thr_qu(reparto), NULL);
pthread_join(THR_INPUT, &result);
pthread_join(THR_QUEUE, &result);
}
else{
wait(sem,0);
pthread_cancel(THR_QUEUE);
printf("---END---\n");
}
exit(EXIT_SUCCESS);
}
and putting a signal in the first thread that, when it is asked to exit, signal to the semaphore in main thread to do the pthread_cancel()
. But it still not working, and i dont know why