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

I have written a 3-thread program using pthread in C ++ and I want to keep the process alive until thread 1 is killed. here is my program:

#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;
}

      

when i run it with "g ++ a.cpp -lpthread" the output looks like this:

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

      

This means that when thread1 is killed, the entire process will be killed. Is there a way to keep the process alive while one of its threads is killed? I need this because I want to use other threads of the process, however any of the threads will be killed. please note that I don't want to use exception handling to avoid killing the thread.

+3


source to share


3 answers


I solved my problem by ignoring the FPE signal. Here's my new program:

#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;
}

      

and its output looks like this:



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

      

this means that when thread1 is killed, the entire process will not be killed and the following threads can perform their functions.

+2


source


You might want to use synchronization mechanisms such as semaphores (using sem_wait (), sem_post ()) that are shared among multiple threads to cause latency.



An alternative way is to use while (1) and sleep () inside func (), but it consumes cpu cycles on wakeup.

-1


source


just use try / catch ?!

This should fix your problem.

-1


source







All Articles