0

I an learning pthread and I have a few questions.

Here is my code:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#define NUM_THREADS 10

using namespace std;

void *PrintHello(void *threadid)
{
   int* tid;
   tid = (int*)threadid;
   for(int i = 0; i < 5; i++){
     printf("Hello, World (thread %d)\n", *tid);
   }
   pthread_exit(NULL);
}

int main (int argc, char *argv[])
{
   pthread_t threads[NUM_THREADS];
   int rc;
   int t;
   int* valPt[NUM_THREADS]; 

   for(t=0; t < NUM_THREADS; t++){
      printf("In main: creating thread %d\n", t);
      valPt[t] = new int();
      *valPt[t] = t;
      rc = pthread_create(&threads[t], NULL, PrintHello, (void *)valPt[t]);
      if (rc){
         printf("ERROR; return code from pthread_create() is %d\n", rc);
         exit(-1);
      }
   }
   /* Last thing that main() should do */
   pthread_exit(NULL);
}

The code runs well and I don't call pthread_join. So I want to know, is pthread_join a must?


Another issue, is:

valPt[t] = new int();
*valPt[t] = t;
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)valPt[t]);

equal to:

rc = pthread_create(&threads[t], NULL, PrintHello, &i);
Jonny Henly
  • 4,023
  • 4
  • 26
  • 43
BlackMamba
  • 10,054
  • 7
  • 44
  • 67
  • The answer to your second question: uh, those two look completely and utterly different to me. My recommendation is to use `reinterpret_cast(i)`, since this is C++ and not C as the question was tagged. – Dietrich Epp Jun 29 '16 at 04:24
  • Here's a discussion of passing values to `pthread_create`: http://stackoverflow.com/questions/8487380/how-to-cast-an-integer-to-void-pointer/8487738#8487738 – Dietrich Epp Jun 29 '16 at 04:25
  • A thread is "freed" either when you join it, or when it finishes if it's detached. If it's not detached and you don't join it, you're leaking it. – user253751 Jun 29 '16 at 05:08
  • 1
    1. `pthread_join` is a must because the main thread (the one that creates the other threads) may finish execution before the created threads finish, and you will usually create threads for lengthy tasks. It is also a way to synchronize threads. 2. You don't really need valPt (and you are also leaking valPt[t] right now). – Fara Importanta Jun 29 '16 at 07:12

1 Answers1

1

It is not. But you need either pthread_exit() or pthread_join(). Here you called pthread_exit(), thats why the child threads continue execution even after the main thread terminates. If there is any need for the main thread to wait till the child threads complete execution, you can use pthread_join().

Twinkle
  • 514
  • 3
  • 8
  • So calling exit() in one of the parallel threads will terminate main and the siblings die a "dirty" death ? but pthread_exit() allows them to run on, possibly terminating gracefully and early if they are aware the parent is gone? More importantly the parent may not be main ? – mckenzm Mar 10 '17 at 04:04