How to reuse a pthreads?
I am 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 would like to know if there is any way to reuse a pthread after pthread_exit(NULL)
.
2
2 answers
The function pthread_exit
, waits for all threads to be terminated to terminate the system. So 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);
}
0
Author: Brumazzi DB, 2016-07-23 05:54:25
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 function ReceivePinPad
// pthread_detach(pthread_self()); // nao faz sentido aqui
// termina a thread (como se fosse um return da funcao ReceivePinPad)
pthread_exit(NULL);
0
Author: zentrunix, 2019-04-06 16:38:57