| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 
 | //Thread.h
 
struct Thread_info {
	struct arg			arg;
	pthread_t			thread;
	pthread_mutex_t		mutex;
	long*				remaining_time;
};
 
class Thread{
private: 
	struct Thread_info	Thread_info;	
	static void*		Thread::Thread_function(void* arg);
 
public:    
	int			Start();
	long		getRT();
};
 
//Thread.cpp
 
void* Thread::Thread_function(void* arg){
	Thread *thread = (Thread*) arg;
		process_1(&(thread->Thread_info.mutex),thread->Thread_info.remaining_time);	
	return NULL;
}
 
int Thread::Start(){
	this->Thread_info.mutex = PTHREAD_MUTEX_INITIALIZER;
	if ( pthread_create( &(this->Thread_info.thread), NULL,Thread::Thread_function,(void *)this) ){
		printf("error creating thread.");
		return 1;
	}
	return 0;
}
 
long Thread::getRT(){
	long ii;
	pthread_mutex_lock(&(this->Thread_info.mutex));
	ii = *(this->Thread_info.remaining_time);
	pthread_mutex_unlock(&(this->Thread_info.mutex));
	return ii;
}
 
int process_1( pthread_mutex_t* mutex, long* remaining_time)
{
	int N = 30;
	time_t t1, t2, t3;
	t1 = time(NULL);
	for (int ii = 0;ii<N;ii++)
	{
		Sleep(1000); //traitement
		t2 = time(NULL);
		t3=(N-ii-1)*(t2-t1)/(ii+1);
		cout<<t3<<endl;
		pthread_mutex_lock(mutex);
		*remaining_time = (long)t3;
		pthread_mutex_unlock(mutex);
	}
	return 0;
}
 
//main.cpp
 
void main()
{
	char num[3];
	int num_function, a;
	long b;
 
	Thread *tab_Thread;
	tab_Thread = new Thread[50];
 
	int ii=0;
	while (1){
	cout<<"Lequel ?"<<endl;
	cout<<" 1: lancer thread.\n 2: get time"<<endl;
	cin >> num;
	sscanf(num, "%d", &num_function);
	if (num_function==1){
			ii++;
			a = tab_Thread[ii].Start();
			cout<<a<<endl;
	}
	else
		if (num_function==2){
			b = tab_Thread[ii].getRT();
			cout<<b<<endl;
			//delete *tab_Thread[ii];
		}
 
} | 
Partager