开发者

Know if a pthread thread is Alive in a safe way

I made a multithread application that generates/destroy 100 threads continuously:

//Here is the thread class (one by every thread
struct s_control
{
   data_in[D_BUFFER_SIZE];//data in to thread
   data_out[D_BUFFER_SIZE];//data generated by the thread
   //I use volatile in order to status data is avaiable in and out of the thread:
   volatile __int16 status;//thread state 0=empty,1=full,2=filling (thread running)
}*control;

//Here is the thread main function    
static void* F_pull(void* vv)//=pull_one_curl() 
{
   s_control* cc = (s_control* ) vv;
   //use of cc->data_in and filling of cc->data out      
   cc->status=1;  //Here advises that thread is finished and data out is filled
   return NULL;
}

void main()
{
   initialization();
   control=new s_control[D_TAREAS];
   pthread_t *tid=new pthread_t[D_TAREAS];
   for (th=0;th<D_TAREAS;th++)
   {  //Access to status of thread at the beginning 
      //(to avoid if it changes in the middle):
      long status1=control[th].status
      if (status1==0)            //Thread finished and data_out of thread is empty
      { control[i2].status=2;    //Filling in (thread initiated)status LLENANDO
        error = pthread_create(&tid[th开发者_如何学Go],NULL,F_pull,(void *) &control[th]);
      }
      else if (status1==1) //Thread finished and data_out of thread is full
      {
         //do things with control[th].data_out;
         //and fill in control[th].data_in with data to pass to next thread
         control[th].status=0;    //Thread is finished and now its data_out is empty
      }
      else 
      {
        //printf("\nThread#%li:filling",i2);
      }
   }while(!_kbhit());
   finish();
}

Then as you can see, at the end of the thread, I used the variable volatile to advise that thread is about to exit:

begin of thread{ ....
   cc->status=1;  //Here advises that thread is finished and data out is filled
   return NULL;
}//END OF THREAD

But after cc->status is set to 1 thread is not finished yet (it exist one more line)

So I do not like set status inside the thread. I tried pthread_kill, but it didn´t work, because it does not work until thread is alive, as can be seen at: pthread_kill


I am not sure if this answers your question, but you can use pthread_join() to wait for a thread to terminate. In conjunction with some (properly synchronized) status variables, you should be able to achieve what you need.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜