How to reuse a pthreads?

Asked

Viewed 292 times

2

I’m using pthread.h and using the following functions:

//
// Cria A thread
//
thread_argsPP[contthreadsPP]        =   contthreadsPP;
pthread_create(&threadsPP[contthreadsPP], NULL,  ReceivePinPad, (void *)    &thread_argsPP[contthreadsPP]);

//
//  Inicia a thread
//
pthread_join(threadsPP[contthreadsPP], NULL);

//
//  Fecha a thread Recive
//
pthread_detach(pthread_self());
pthread_exit(NULL);

But after closing the thread I can’t recreate it, I wonder if there’s any way to reuse a pthread after the pthread_exit(NULL).

  • Of what types are the variables thread_argsPP, contthreadsPP and threadsPP? Please paste their statement as this is essential to understand your problem. It seems to me you are losing the reference to some of the objects/ structures when you could not.

2 answers

0

There is no way you can "reuse" the thread, what you can do is recreate the thread.

In the program that creates the thread:

for (;;)
{
  // testa algum criterio para nao (re)criar a thread
  if (...)
    break;

  // cria thread
  thread_argsPP[contthreadsPP] = contthreadsPP; // ??? isso faz sentido
  pthread_create(&threadsPP[contthreadsPP], NULL, ReceivePinPad, (void*)&thread_argsPP[contthreadsPP]);

  // espera a thread terminar
  pthread_join(threadsPP[contthreadsPP], NULL);
} // volta para proxima iteracao do for

Inside the Receivepinpad function

// pthread_detach(pthread_self()); // nao faz sentido aqui
// termina a thread (como se fosse um return da funcao ReceivePinPad)
pthread_exit(NULL);

0

The function pthread_exit, expects all the Threads shut down to terminate the system. Then it would be the same thing as using a exit.

But if you want to reuse threads, you can use a counter to wait for them to finish, you can use a counter to know how many threads are running.

int count;

void thread_call(void *data){
    ...
    count--;
}

void main(){
    ...
    for(...){ // cria as threads
        ...
        count++;
    }
    while(count); // espera as threads terminarem;
    for(...){ // re-instancia as threads
        ...
        count++;
    }

    pthread_exit(0);
}
  • Thank you, but my problem is not exactly this, even after the pthread finished I can’t recreate it using the pthread_create and pthread_join, I wanted to know if there’s any way I can do this, an example: I create pthread 1 even though she’s at the end, exit(), I can’t create it again, s create the pthread 2 with the same function, only a new

  • this answer is wrong..."pthread_exit" ends the thread in which it is called, as if it were a "Return" command...something else, that Busy loop "while (Count);" is extremely inadvisable...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.