Узнайте, безопасна ли нить pthread - PullRequest
0 голосов
/ 14 февраля 2011

Я создал многопоточное приложение, которое непрерывно генерирует / уничтожает 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-> status установлено значение 1, поток еще не завершен (существует еще одна строка)

Поэтому мне не нравится установка статуса внутри потока.Я пробовал pthread_kill, но он не работал, потому что он не работает, пока поток не активен, как можно увидеть по адресу: pthread_kill

1 Ответ

1 голос
/ 14 февраля 2011

Я не уверен, отвечает ли это на ваш вопрос, но вы можете использовать pthread_join (), чтобы дождаться завершения потока.В сочетании с некоторыми (правильно синхронизированными) переменными состояния вы сможете достичь того, что вам нужно.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...