条件变量对多线程求素数的改进

代码

#define LEFT 30000000
#define RIGHT 30000200
#define SIZE 4

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
//0代表池中没有任务 >0 代表有任务 -1代表全部计算完成
int nPool = 0;


void * Fun(void *p)
{
    
    
   int nNum;
   int Flag;
   int j;


   while(1)
   {
    
    
           Flag = 1;
           pthread_mutex_lock(&mutex);

           while(0 == nPool && -1 != nPool)
           {
    
    
                   pthread_cond_wait(&cond, &mutex);

                   /*pthread_mutex_unlock(&mutex);
                   sched_yield();
                   pthread_mutex_lock(&mutex);*/

           }

           nNum = nPool;
           nPool = 0;
           //必须唤醒所有的线程 因为main线程在里面
           pthread_cond_broadcast(&cond);

           pthread_mutex_unlock(&mutex);

           if(RIGHT == nNum || -1 == nNum)
           {
    
    
                   nPool = -1;
                   break;
           }

           for(j = 2; j < nNum/2; j++)
           {
    
    
                   if(0 == nNum % j)
                   {
    
    
                           Flag = 0;
                   }
           }

           if(Flag)
           {
    
    
                   printf("[%d] %d is a prime\n", (int)p, nNum);
           }
   }

   printf("%d Out \n", (int )p);

   pthread_exit(NULL);
}

int main()
{
    
    
   pthread_t tid[SIZE];
   int i,err;


   for(i = 0 ; i < SIZE; i++)
   {
    
    
           err = pthread_create(tid+i, NULL, Fun, (void *)i);
           if(err)
           {
    
    
                   fprintf(stderr, "create()%s ", strerror(err));
                   exit(1);
           }

   }


   for(i = LEFT; i <= RIGHT; i++)
   {
    
    
           pthread_mutex_lock(&mutex);

           while(0 != nPool && -1 != nPool)
           {
    
    
                   pthread_cond_wait(&cond, &mutex);

                   /*pthread_mutex_unlock(&mutex);
                   sched_yield();
                   pthread_mutex_lock(&mutex);*/

           }

           if(-1 != nPool)
                   nPool = i;
            //下面四个线程 任意唤醒一个
           pthread_cond_signal(&cond);

           pthread_mutex_unlock(&mutex);
   }



   for(i = 0; i < SIZE; i++)
   {
    
    
           pthread_join(tid[i], NULL);

   }


   pthread_mutex_destroy(&mutex);
   pthread_cond_destroy(&cond);

   return 0;
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/ZZHinclude/article/details/119719498