多线程计算质数:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#define LEFT 30000000
#define RIGHT 30001000
#define THRNUM 4
int value = 0;
pthread_cond_t full = PTHREAD_COND_INITIALIZER;
pthread_cond_t empty = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void primer( int idx, int val )
{
int i = 0;
for( i = 2; i < val; i++ ){
if( val % i == 0 ){
// printf( "val[%d] isnot primer\n", val );
return;
}
}
printf( "[%d] == [%d] is primer\n", idx, val );
}
void* routine( void *arg )
{
int idx = ( int )arg;
while( 1 ){
pthread_mutex_lock( &mutex );
while( value == 0 ){
pthread_cond_wait( &full, &mutex );
}
if( value == -1 ){
pthread_mutex_unlock( &mutex );
pthread_exit( NULL );
}
int val = value;
value = 0;
pthread_cond_broadcast( &empty );
pthread_mutex_unlock( &mutex );
primer( idx, val );
}
}
int main()
{
pthread_mutex_init( &mutex, NULL );
pthread_t tid[THRNUM];
int i = 0;
for( i = 0; i < THRNUM; i++ ){
pthread_create( tid + i, NULL, routine, (void *)i );
}
for( i = LEFT; i < RIGHT; i++ ){
pthread_mutex_lock( &mutex );
while( value != 0 ){
pthread_cond_wait(&empty, &mutex);
}
value = i;
pthread_cond_broadcast( &full );
pthread_mutex_unlock( &mutex );
}
pthread_mutex_lock( &mutex );
while( value != 0 ){
pthread_cond_wait(&empty, &mutex);
}
value = -1;
pthread_cond_broadcast( &full );
pthread_mutex_unlock( &mutex );
for( i = 0; i < THRNUM; i++ ){
pthread_join( tid[i], NULL );
}
pthread_mutex_destroy( &mutex );
}
下面为验证代码:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#define LEFT 30000000
#define RIGHT 30001000
#define THRNUM 4
int value = 0;
pthread_cond_t full = PTHREAD_COND_INITIALIZER;
pthread_cond_t empty = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void primer( int idx, int val )
{
int i = 0;
for( i = 2; i < val; i++ ){
if( val % i == 0 ){
// printf( "val[%d] isnot primer\n", val );
return;
}
}
printf( "[%d] == [%d] is primer\n", idx, val );
}
void* routine( void *arg )
{
int idx = ( int )arg;
while( 1 ){
pthread_mutex_lock( &mutex );
while( value == 0 ){
pthread_cond_wait( &full, &mutex );
}
if( value == -1 ){
pthread_mutex_unlock( &mutex );
pthread_exit( NULL );
}
int val = value;
value = 0;
pthread_cond_broadcast( &empty );
pthread_mutex_unlock( &mutex );
primer( idx, val );
}
}
int main()
{
int i = 0;
for( i = LEFT; i < RIGHT; i++ ){
primer( 0, i );
}
}