Sin impresión de cout en la función de inicio de pthread

i'm new here and noob with pthread programming. My problem is in a C++ class, that i'm trying to create to encapsulate a thread. Reading around i'd seen that when i create a pthread, i need to pass a C function to pthread_create that it runs on startup... So, when the pthread runs that function it doesn't cout the message on stdout!

But it's better if you see the code: (obviously it's copy and pasted from an internet tutorial ^^)

void *runAtStart( void *threadid)
{

    long tid;
   tid = (long)threadid;

   printf("Hello World! It's me, thread #%ld!\n", tid);
   pthread_exit(NULL);
}


Thread::Thread() {
    pthread_t threads[1];
   int rc;
   long t;
   for(t=0; t<1; t++){
      printf("In main: creating thread %ld\n", t);
      rc = pthread_create(&threads[t], NULL, runAtStart, (void *)t);
      if (rc){
         printf("ERROR; return code from pthread_create() is %d\n", rc);
        // exit(-1);
      }
   }
}

in the main i call this as:

int main()
{
    Thread *th=new Thread();
    return 0;
}

the output generated is:

In main: creating thread 0

i hope that someone has understood! sorry for my English! :) Inzirio

preguntado el 10 de marzo de 12 a las 15:03

1 Respuestas

Your program runs fine. The problem you're seeing is that your main() function returns before your thread can actually run, and this causes your program to exit.

A simple way to prove this is to add sleep(5); in main(), prior to your return call. A better way is to find a manner to cause main() to wait until all of its threads have completed before it returns. One reasonable manner to do that is to add a destructor to your Thread class that performs a pthread_join, and be sure you actually call the destructor: delete th;

respondido 10 mar '12, 15:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.