当其中一个线程在 C++ 中使用 pthread 被杀死时,我如何保持进程的存活

How I can keep alive the process while one of its threads is killed using pthread in C++?

本文关键字:何保持 进程 一个 线程 C++ pthread      更新时间:2023-10-16

我在 c++ 中使用 pthread 编写了一个包含 3 个线程的程序,我想在线程 1 被杀死时保持进程的活动状态。 这是我的程序:

#include <unistd.h>
#include <pthread.h>
#include <iostream>
using namespace std;
int a = 0;
void *func (void *arg)
{
   int c = a++;
   cout << "start thread " << c << endl;
   if (c == 1) //I wrote this to thread1 crashes and be killed.
   {
     int d = 0;
     d = 10 / d;
   }
   cout << "end thread " << c << endl;
}
int main ()
{
   pthread_t tid1, tid2, tid3;
   pthread_create (&tid1, 0, func, 0);
   sleep (1);
   pthread_create (&tid2, 0, func, 0);
   sleep (1);
   pthread_create (&tid3, 0, func, 0);
   sleep (10);
   return 0;
}

当我使用"g++ a.cpp-lpthread"运行时,输出如下所示:

start thread 0
end thread 0
start thread 1
Floating point exception (core dumped)

这意味着当线程 1 被杀死时,整个进程将被杀死。 有没有办法在进程的一个线程被杀死时保持活动状态?我需要它,因为我想使用进程的其他线程,但是任何线程都被杀死。
请注意,我不想使用异常处理来避免杀死线程。

我通过忽略FPE信号解决了我的问题。这是我的新程序:

#include <unistd.h>
#include <pthread.h>
#include <iostream>
#include <signal.h>
using namespace std;
int a = 0;
void sig_func(int sig)
{
  //some code we want execute when signal recieves, or nothing.
}
void *func (void *arg)
{
  int c = a++;
  cout << "start thread " << c << endl;
  if (c == 1)
  {
    int d = 0;
    d = 10 / d;
  }
  cout << "end thread " << c << endl;
}
int main ()
{
  pthread_t tid1, tid2, tid3;
  signal(SIGFPE,sig_func);
  pthread_create (&tid1, 0, func, 0);
  sleep (1);
  pthread_create (&tid2, 0, func, 0);
  sleep (1);
  pthread_create (&tid3, 0, func, 0);
  sleep (10);
  return 0;
}

它的输出是这样的:

start thread 0
end thread 0
start thread 1
start thread 2
end thread 2

这意味着当 thread1 被杀死时,整个进程不会被杀死,下一个线程可以运行它们的函数。

您可能希望使用同步机制,例如在多个线程之间共享的信号量(使用 sem_wait((,sem_post(((来诱导延迟。

另一种方法是在 func(( 中使用 while(1( 和 sleep((,但在唤醒时消耗 CPU 周期。