多线程计算质数

多线程计算质数:

#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 );
	}
		
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值