【发布时间】:2021-12-06 20:37:18
【问题描述】:
我正在创建两个独立运行的线程。当其中一个线程出现错误时,我会从该特定线程返回并返回值 -1。但我想杀死另一个线程并优雅地终止/退出进程。我如何做到这一点?
pthread_t thr1, thr2;
void *func1(void *args)
{
while(1){
.....
if(/*error*/) {
return (void *)-1;
}
}
return (void *)0;
}
void *func2(void *args)
{
while(1){
.....
if(/*error*/) {
return (void *)-1;
}
}
return (void *)0;
}
int main(){
....
if(pthread_create(&thr1, NULL, func1, NULL) != 0) {
return -1;
}
if(pthread_create(&thr2, NULL, func2, NULL) != 0) {
return -1;
}
/* If all goes well, do pthread_join for both threads,
but if I return error, i.e. -1 from thread functions,
how do I kill the other and exit the process? */
(void)pthread_join(thr1, NULL);
(void)pthread_join(thr2, NULL);
return 0;
}
【问题讨论】:
-
一旦你杀死一个线程,就没有什么是优雅的了。 devblogs.microsoft.com/oldnewthing/20150814-00/?p=91811 - 你最好以某种方式通知线程它应该自行退出。
-
here 中的一些答案可能会有所帮助。
-
为什么不直接调用操作系统的“TerminateProcess()”API,例如。通过中止()?在大多数情况下,用户代码的“优雅退出”是不可取的,(无论如何,在一个非平凡的操作系统上) - 充其量,它是你脖子上的信天翁,随着你开发你的应用程序变得越来越重,并且必须不断重新测试关闭代码.在最坏的情况下,实际上是不可能的,因为某些线程在不透明的库代码中循环/阻塞。
标签: c multithreading pthreads pthread-join