sync.c 2.92 KB

/*************************************************************************
 *
 *  File: sync.c
 *
 *  This file contains the routines to manage synchronization between threads
 *  by using system locks
 *
 *  $Header: /root/leakn64/depot/rf/sw/bbplayer/iosim/src/sync.c,v 1.2 2002/05/30 05:52:50 whs Exp $
 *
 */

#include <sys/types.h>		
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <unistd.h>

#include "sync.h"

#ifdef __sgi__
/***************************************************************************
 * Extern variables
 */

/***************************************************************************
 * Global variables
 */
usptr_t *SyncArena;
ulock_t SyncLock[MAX_LOCK];


/***************************************************************************
 * Create arena for synchronization
 */
static ulock_t
getNewLock(void)
{
	static ulock_t lock;

	if ((lock = usnewlock(SyncArena)) == NULL) {
		perror("usnewlock");
		return(NULL);
	}
	return(lock);

}  /* getNewLock */
#endif

void
SyncInit(void)
{
#ifdef __sgi__
	int	i;
	char	*tmpdir;
	char	arenafile[_POSIX_PATH_MAX];

	if ((tmpdir = getenv("TMPDIR")) != NULL)
		strcpy(arenafile, tmpdir);
	else
		strcpy(arenafile, "/tmp");

	strcat(arenafile, "/emXXXXXX");
	mktemp(arenafile);
	if ((SyncArena = usinit(arenafile)) == NULL) {
		fprintf(stderr, "SyncInit: usinit(%s) failed: %s\n", 
			arenafile, sys_errlist[errno]);
		exit(1);
	}
	if (unlink(arenafile) == -1) {
		fprintf(stderr, "SyncInit: unlink(%s) failed: %s\n", 
			arenafile, sys_errlist[errno]);
		exit(1);
	}

	for (i = 0; i < MAX_LOCK; i++) {
		if ((SyncLock[i] = usnewlock(SyncArena)) == NULL) {
			perror("usnewlock");
			exit(1);
		}
	}
#endif
}  /* SyncInit */

#ifdef __sgi__
int
LockSet(ulock_t lock)
{
	if (ussetlock(lock) == -1) {
		perror("ussetlock");
		return(-1);
	}
	return(0);
}


int
LockReset(ulock_t lock)
{
	if (usunsetlock(lock) == -1) {
		perror("usnsetlock");
		return(-1);
	}
	return(0);
}


void
SysLockSet(void)
{
	if (ussetlock(SYS_LOCK) == -1) {
		perror("ussetlock");
		return;
	}
}


void
SysLockReset(void)
{
	if (usunsetlock(SYS_LOCK) == -1) {
		perror("usnsetlock");
		return;
	}
}

#endif

#ifdef fprintf
#undef fprintf
#endif

/*
 * Logging to file with time and pid stamp; also, uses semaphore locking
 */
int
LogPrintf(FILE *stream, const char *format, ...)
{
        va_list	ap;
	time_t	t;
	char	s1[240];
	char	s2[160];

        va_start(ap, format);

#ifdef LOG_TIME
	t = time(NULL);
	strftime(s1, sizeof(s1), "%T: ", localtime(&t));
	sprintf(s2, "%5d: ", getpid());
        strcat(s1, s2);
        vsprintf(s2, format, ap);
        strcat(s1, s2);
#else
	sprintf(s1, "%5d: ", getpid());
        vsprintf(s2, format, ap);
        strcat(s1, s2);
#endif

#ifdef __sgi__
	ussetlock(LOG_LOCK);
#endif
        fprintf(stream, s1);
        fflush (stream);
#ifdef __sgi__
	usunsetlock(LOG_LOCK);
#endif 

        va_end(ap);

}  /* LogPrintf */