/*
List of mutex flags we need to use for various things

*/
#define MUTEX_MAIN 1
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "emsg.h"
int stat_mutex(int x);
#include "mutex.h"
#ifdef DOTHREADS
void mutex_init(void)
{
	int i;
	for (i=0; m_names[i]!=NULL; i++) {
		mutexes[i] = th_mutex_new(m_names[i]);
	}
}
static int held;
static int start;
void mutex_wait(int i)
{
	if (mutexes[i]==NULL) return;
	if ((i<0) || (i>=MAX_MUTEX)) {
		emsg("No such mutex\n");
		abort();
	}
	if (!th_mutex_wait(mutexes[i],6000000)) { /* 100 minutes */
		emsg("Cannot get mutex, fatal problem, dieing %s\n",m_names[i]);
		abort();
	}
	if (i==M_MAIN) {
		held++;
		if (held==1) start=lib_msec(); 
	}
}
void mutex_release(int i)
{
	if (mutexes[i]==NULL) return;
	if (i==M_MAIN) {
		held--;
		if (held==0) stat_mutex(lib_msec()-start); 
	}
	if (!th_mutex_release(mutexes[i])) {
		emsg("Cannot free mutex, fatal problem, %s\n",m_names[i]);
		abort();
	}
}
#else
void mutex_init(void)
{
}
#endif