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



int number;
int *thread_id;


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

void init() {
//	int j;
 //	for( j=1; j <= number; j++ ) {
//		thread_id[j-1] = j;
//	}//for
	
	pthread_mutex_init( &mutex, NULL );//inicializiruem muteks
	pthread_cond_init( &cond, NULL );//
	pthread_attr_init( &attr );//inicializiruem atrebut
	pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );//delaem atr. - JOINABLE
}//init


void* finish ( void* unused ){
	int i = (int *) unused;//polu4aem peredanii parametr v funkciy
	pthread_mutex_lock( &mutex );//lo4im muteks
	printf(">>>>>>>>%i: finish\n", i);//priwla mawinka na finiw i zaxvatila muteks
	pthread_mutex_unlock( &mutex );//unlo4im nuteks
}//finish


int main( int argc, char *argv[] ) {
	number = atoi( argv[1] );//polu4aem kol. mawinok iz komandnoi stroki
				     //atoi - perevodit v tip INT peremennuy iz kom.strok. STRING
	int iRand,
	    h, temp,
	    flag;// neobhodim v cikle povtorov
	pthread_t thread[number];// indefekator novogo potoka
	int *notRepeat = (int*) malloc(number*sizeof(int));//massiv-proverka, 4to randomon ne sozdana povtorno mawinka(t.e. kotoruy on do etogo sozdal)
	//thread_id = (int*) malloc(number*sizeof(int));//
	init();

	for( h=0; h<number; h++) {//cikl dl9 sozdani9 vsex mawinok
		while( flag != 1 ) {
			flag = 1;
			iRand = 0 + random()%(number-0+1);// eto - random, gde ni*n99 granica -0
							  //a verxn99 - NUMBER, t.e. to 4islo 4to mi vveli v konsole
			for( temp=0; temp<h ; temp++ ) // proverka ne povtor9las li mawinka na starte
				if ( iRand == notRepeat[temp] ) 
					flag = 0; 
				
			}
	
		
		notRepeat[h] = iRand;//zapaminaem 4to za miwinka startanula
		flag =0;
		printf("%i: car starting\n", iRand);
		pthread_create( &(thread[iRand]), &attr, finish, iRand );//sozdaem nitku
	}
	
	pthread_mutex_destroy( &mutex );//ubivaem nuteks
	//pthread_cond_destroy( &cond );
	pthread_attr_destroy( &attr );//ubivaem atrebut
	pthread_exit(NULL);// dl9 togo 4tobi vse nitki *dali poka posledn99 ne otrabotaet, i tolko togda prekratits9 rabota programmi
	
}//main

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