简体   繁体   English

如何从父线程中杀死子线程 - C

[英]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/O 命令上),因此无法接收一些信号或 msg 以完成它们的过程。

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.我想过使用pthread_cancel并覆盖cancel routine但问题是发送cancel signal时某些互斥体似乎被锁定,因此无法销毁。
Using pthread_kill did not work either because it kills the whole process and thus cannot be used when I want a clean exit.使用pthread_kill也不起作用,因为它会杀死整个进程,因此在我想要干净退出时无法使用。

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 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.例如,您可以在线程内为特定信号设置一个等待函数,并在收到相同信号后立即退出线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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