Syncronizing Threads


Problem

int i_init = 0;
pthread_mutex_t * i_mutex;

void i_init_routine()
{
	if (i_init == 0) {
		pthread_mutex_init(i_mutex, NULL);
		i_init = 1;
	}
}

We need to lock a mutex before checking i_init...
pthread_mutex_t * ii_mutex;
void ii_init_routine()
{
	P_M_L(ii_mutex);
	i_init_routine();
	P_M_U(ii_mutex);
}
We need to initialize ii_mutex...


Once Only Function

pthread_once_t once_control = PTHREAD_ONCE_INIT;

int pthread_once(pthread_once_t *, void (*init_routine)(void));


Fixed Problem


pthread_once_t i_init = PTHREAD_ONCE_INIT;
pthread_mutex_t * i_mutex;

void i_init_routine()
{
	pthread_mutex_init(i_mutex, NULL);
}

void ii_init_routine()
{
	pthread_once(&i_init, i_init_routine);
}


[TOP] [BACK] [FORWARD]


Prepared by Chris Provenzano (proven@mit.edu)