简体   繁体   中英

How to Kill child threads from Parent thread - C

I have a little program with few processes, each process contains several threads.

When the parent process receives a specific message it is supposed to kill all its sub threads and destroy all the mutexes. The problem is that some of this threads can be blocked (on I/O command) and thus cannot receive some signal or msg in order to finish their procedures.

I thought about using pthread_cancel and override the cancel routine but the problem is that some mutexes appeared to be locked when the cancel signal is sent, and thus cannot be destroyed.
Using pthread_kill did not work either because it kills the whole process and thus cannot be used when I want a clean exit.

How can a process kill its child threads and destroy the mutexes in a clean fashion?

The relevant section of the code looks as something like :

ret = fork()
if(ret > 0) {
    pthread_t th1, th2;
    my_pthread_create(&th1, threadFunction1, NULL);
    my_pthread_create(&th2, threadFunction2, NULL);
    if(msgrcv(qid1, &msg, MSG_SIZE,0,0) < 0) {
        perror("msgrcv failed...\n");
    } else {
        //print some information from the global variables, terminate 
        //threads and destroy mutexes
    }
}
else if(ret<0) {
    perror("fork failed...\n");
} else {
    ....
}

Any help will be really appreciated!
Thank you

scoped_lock

is one of the best options you can go with, That would automatically release the mutex when the program execution goes out of scope.

With that said I would not recommend killing the threads in a production ready code unless it is really necessary and there is no other option to go with, you can also use signaling mechanisms to notify the threads to die by themselves that would avoid a lot of problems. Say for example you can have a wait function inside a thread for a specific signal and exit the thread as soon as you receive the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM