知道pthread线程是否以安全的方式生效

时间:2011-02-14 13:20:43

标签: c++ c pthreads

我创建了一个多线程应用程序,可以连续生成/销毁100个线程:

//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],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();
}

然后如您所见,在线程结束时,我使用变量volatile建议线程即将退出:

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

但是在cc-&gt;状态设置为1后,线程尚未完成(它还存在一行)

所以我不喜欢在线程中设置状态。 我尝试了pthread_kill,但它不起作用,因为它在线程处于活动状态之前不起作用,如下所示: pthread_kill

1 个答案:

答案 0 :(得分:1)

我不确定这是否能回答您的问题,但您可以使用pthread_join()等待线程终止。结合一些(正确同步的)状态变量,您应该能够实现所需。