Скачиваний:
13
Добавлен:
01.05.2014
Размер:
2.32 Кб
Скачать
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>

#define NUM_THREADS 10

int thread_id [NUM_THREADS];
//enum State {FIRE, SLEEP, SHOT};
int NUMBER = 0; //number of rifleMen
int thread_priority = 0;


pthread_mutex_t mutex;
pthread_cond_t cond;
pthread_attr_t attr;
sem_t sem;

void init() {
	int j;
	for( j=1; j <= NUM_THREADS; j++ ) {
		thread_id[j-1] = j;
	}//for
	
	pthread_mutex_init( &mutex, NULL );
	pthread_cond_init( &cond, NULL );
	pthread_attr_init( &attr );
	pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
}//init


void* rifleMan ( void* unused ){
	int i = (int *) unused;
	//int myNumber = (int *) unused;
	int myNumber1 = 0;

	
	
	//printf("Thread number = %d\n", i);
//The 1 state	
	

			//printf("thread %d wait.\n", i);
			pthread_mutex_lock( &mutex );
			
			printf("%d: sleep \n", i);
			pthread_cond_wait( &cond, &mutex );
			pthread_cond_signal(&cond);//send signal to following rifleMan
			pthread_mutex_unlock( &mutex );
			//printf("thread %d condition signal receved.\n", i );	
		
	

//The 2 state
	//pthread_mutex_lock( &mutex );
	pthread_mutex_lock( &mutex );

	NUMBER = NUMBER+1;
	myNumber1 = NUMBER;
	printf("%d: fire \n", i, myNumber1);
	if (myNumber1 != NUM_THREADS )	{
		
		while( myNumber1 != thread_priority ) 
			pthread_cond_wait( &cond, &mutex );
		//printf("while_%d, %d \n", thread_priority, myNumber1);
		thread_priority = myNumber1 -1 ;
		pthread_cond_broadcast(&cond);
		
	} else{
		thread_priority = myNumber1 - 1;
		//printf("else_%d, %d \n", thread_priority, myNumber1);
		pthread_cond_broadcast(&cond);
	}
	
	
//The 3 state		
	printf("%d: make_ready \n", i);
pthread_mutex_unlock( &mutex );
	sleep( myNumber1 );	

//The 4 state
	printf("%d: shot \n", i);
	
	

}//rifleMan


void* fire( void* unused ) {
	printf("Start: officer\n");
	//pthread_cond_broadcast(&cond);
	pthread_cond_signal(&cond);
}//free


int main() {
	int i;
	pthread_t thread[NUM_THREADS];	
	pthread_t officer;
	init();
		
	for( i=1; i <= NUM_THREADS; i++ ) {
		pthread_create( &(thread[i-1]), &attr, rifleMan, thread_id[i-1] );	
	}//for
	
	pthread_create( &officer, NULL, fire, NULL );
	pthread_join( officer, NULL );	

	pthread_mutex_destroy( &mutex );
	pthread_cond_destroy( &cond );
	pthread_attr_destroy( &attr );
	pthread_exit(NULL);

}//main

Соседние файлы в папке Лабораторная работа №33