Abhishek
Abhishek

Reputation: 283

malloc memory for pthread and then fork + execvp

I get an event and based on that event i do some processing and then fork + execvp some other program (called some_jazzy_program). Initially i used a while loop where i did the following:

 while (some condition)
 {
      pid = fork();

      if (pid == 0)
      {
            do_some_work()

            execvp (some_jazzy_program..);
      }
      else 
      {
            do_some_bookkeeping();
      }
 }

The problem with this design is that if do_some_work() takes up large amount of time then i am not able spawn new processes fast enough to launch some_jazzy_program. To fix this, i started using pthreads:

  pthread_t *work_threads[MAX_FORKS_ALLOWED];

  while (some condition)
  {
      work_threads[index] = (pthread_t *) malloc (sizeof (pthread_t));

      pthread_create(work_threads[index], NULL, do_some_good_work, NULL);

      index ++;
  }

  void * do_some_good_work (void *arg)
  {
      pid = fork();

      if (pid == 0)
      {
            do_some_work()

            execvp (some_jazzy_program..);
      }
      else 
      {
            do_some_bookkeeping();
      }
 }  

This design works. However, i have a few questions.

The fork + excvp is called which spawns a new process. Where should i call pthread_exit() in the parent program. With whatever i have read, i dont necessarily need to call pthread_exit since the thread automatically dies when the work its set out to do completes. In this context as soon as i do a fork + execvp it would die.

My other concern is about the work_threads[index] = (pthread_t *) malloc (sizeof (pthread_t)) -- the memory malloc that i am doing. When i use malloc i allocate memory from the heap. Where can i free this memory and release it back to the heap. Not doing anything looks like a memory leak to me.

Is what i am attempting here usually done -- first run multiple pthreads and within each pthread do a fork + execvp

Upvotes: 0

Views: 510

Answers (1)

cppcoder
cppcoder

Reputation: 23135

Regarding your first problem, you need not call pthread_exit. If your main program want to keep track of the threads, you may use pthread_join and check the return status of the threads.

Regarding your second problem, you can avoid heap memory allocation by just using:
pthread_t work_threads[MAX_FORKS_ALLOWED];

Regarding your third question, as Joachim said, it is not common to fork inside a thread; in fact a little dangerous too. Think before you mix them

Upvotes: 1

Related Questions