monitor.c 1.16 KB
Newer Older
Michele Porta's avatar
Michele Porta committed
1 2 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
#include <pthread.h>
#include <stdlib.h>

#include "monitor.h"
#include "task.h"


void set_stato(task_monitor* m, stato_task s, int task_index){
	pthread_mutex_lock(&m->mutex);
	m->stato[task_index] = s;
	pthread_mutex_unlock(&m->mutex);
}

stato_task get_stato(task_monitor* m, int task_index){
	stato_task s;	
	pthread_mutex_lock(&m->mutex);
	s = m->stato[task_index];
	pthread_mutex_unlock(&m->mutex);
	return s;
}


void init_monitor(task_monitor* m, int num_tasks){
	int i;
	m->cond = malloc(sizeof(pthread_cond_t) * num_tasks);
	m->stato = malloc(sizeof(stato_task) * num_tasks);
	pthread_mutex_init(&m->mutex, NULL);

	for(i=0;i<num_tasks;i++){
		pthread_cond_init(&m->cond[i], NULL);
	}
}

void wait_monitor(task_monitor* m, int task_index){
	pthread_mutex_lock(&m->mutex);
	m->stato[task_index] = IDLE;
	while(m->stato[task_index] != PENDING){
		pthread_cond_wait(&m->cond[task_index], &m->mutex);
	}	
	m->stato[task_index] = WORKING;
	pthread_mutex_unlock(&m->mutex);
}

void monitor_destroy(task_monitor* m, int num_tasks){
	int i;
	for(i=0;i<num_tasks;i++){
		pthread_cond_destroy(&m->cond[i]);
	}
	free(m->cond);
	free(m->stato);
	pthread_mutex_destroy(&m->mutex);
	free(m);
}