代码
#define LEFT 30000000
#define RIGHT 30000200
#define SIZE 4
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
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);
}
nNum = nPool;
nPool = 0;
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);
}
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;
}
