pthread - 条件信号和等待

时间:2014-03-28 09:07:56

标签: c linux multithreading pthreads

所以我目前正在尝试使用pthread进行一些操作,但是我一直在遇到一些问题,我认为应该工作。在这个非常未完成的例子中,我试图用'y'线程来操纵'x'数据量。所以我制作了2个结构,1个用于'x'数据量,1个用于'y'数量的线程。线程的结构有一个指向数据结构的指针,所以我可以在不重新创建线程或将整个数据集传递给线程的情况下切换它们。

无论如何,当我运行当前版本的程序时,我遇到了问题。没有线程池已经完成,因为我还没有达到那么远。它应该做的是在每个线程的循环中打印出一些信息。它应该在我发出信号时开始。但是条件信号似乎没有正常工作,因为并非所有线程都被激活......

我希望有人可以帮助我!

#include <pthread.h>
#include <stdio.h>    
#include <stdlib.h>    
#include <unistd.h>    
#include <time.h>

#define NUM_THREADS     5    
#define NUM_LOOP        50



typedef struct infos {

   int real;    

} infos;



typedef struct thread_specs {

   infos          *infos;

   int thread_id;

   pthread_mutex_t mutex_condition;    
   pthread_cond_t  cond_wait;    

} thread_specs;




/* some trivial work to be done  but it should wait on the conditional wait*/
void *printtest(void *arg) {

   int i,sleep;
   thread_specs *thread_stuff= (thread_specs*)(arg);

    while (1) {
      pthread_cond_wait( &(thread_stuff->cond_wait) , &(thread_stuff->mutex_condition) );

         for (i=0;i<5;i++) {
            sleep=rand()%100000;
            printf("thread: %6i | loop: %2i\n",thread_stuff->thread_id,i); // thread_stuff->infos.real
            usleep(sleep);
         }
   }
}





int main () {

   pthread_t         threads[NUM_THREADS];

   infos             infostruct[NUM_LOOP];

   thread_specs      thread_info[NUM_THREADS];

   size_t            i;

   srand(time(0));

   for (i=0;i<NUM_THREADS;i++) {
      // setting the current loop into the thread_info struct and the info struct, later this would be more complex data but as an example it should suffice
      thread_info[i].thread_id=i;
      pthread_mutex_init(&(thread_info[i].mutex_condition), NULL);
      pthread_mutex_lock(&(thread_info[i].mutex_condition));
      infostruct[i].real=i;

      thread_info[i].infos=&infostruct[i];

   }


  // creating threads and passing a single index from the struct to it. later the infos struct pointer would be rotated to allow for different manipulation of data
   for (i=0;i<NUM_THREADS;i++) {
      if (pthread_create(&threads[i], NULL, printtest, &thread_info[i] )) {
         printf("ERROR creating thread");
      } else {
         printf("SUCCES creating thread #%i\n",i);
      }
   }

   printf("created all thread\n");

  // trying to signal all threads to start their work, make sure there mutex is unlocked so they are waiting for a the condition.
   for(i=0;i<NUM_THREADS;i++) {
      pthread_mutex_lock(&(thread_info[i].mutex_condition));
      pthread_mutex_unlock(&(thread_info[i].mutex_condition));
      pthread_cond_signal(&(thread_info[i].cond_wait));
   }

   printf("signaled condition\n");

   sleep(10);

   printf("\n!!DONE!!\n");

}  

1 个答案:

答案 0 :(得分:1)

您使用pthread_cond_wait完全错误。它只能在你的线程持有互斥锁时工作。它们的全部技巧是pthread_cond_wait版本在等待期间暂时保留在互斥锁上,并在返回时重新归属。

同样,对pthread_cond_signal的调用最好放在里面持有锁定的关键部分,而不是之后。