#pragma ident "$Header: /san01/cvs/ashpool/csrc/moddynamo/Attic/threadabstr.c,v 1.2 2004/03/18 15:04:15 aleigh Exp $"

/* Copyright (c) 1994, 2001 Alex Leigh, All Rights Reserved
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF ALEX LEIGH
 * The copyright notice above does not evidence any
 * actual or intended publication of such source code.
 * 
 * Disclosure, copying, distribution, or transmission of of
 * this code without express permission is prohibited.
 */

/*
 * threadabstr.c : evolution thread interface for dynamo CM PURE LIQUID EVIL
 * Alex Leigh (aleigh@tessier.com) 2001
 */

#include <time.h>
#include <sys/time.h>

#include "threadabstr.h"

/*
 * thread_startNewThread(kThread_defaultStackSize, cmldrpThreadFunction,
 * (kThread_argType) pBlock); if (gCMLDRPThread == kThread_InvalidThread) {
 * gCMLDRPBlock.logFunction(gCMLDRPBlock.logShellData, kLog_Error,
 * kLogMessage_CannotStartCMLDRPThread, NULL, NULL); returnValue = -1; }
 */

Thread_t thread_startNewThread(int StackSize, void *start_func(void *),
                               void *arg)
{
    pthread_t tid;

    pthread_create(&tid, NULL, start_func, arg);

    return tid;
}

/* TODO: This function does not support the timeout value */
int getReadLock(RWLock * lock, int timeout)
{
    return pthread_rwlock_rdlock(lock);
}

/* TODO: This function does not support the timeout value */
int getWriteLock(RWLock * lock, int timeout)
{
    return pthread_rwlock_wrlock(lock);
}

int releaseWriteLock(RWLock * lock)
{
    return pthread_rwlock_unlock(lock);
}

int releaseReadLock(RWLock * lock)
{
    return pthread_rwlock_unlock(lock);
}


/* if (initializeRWLock(&gLoadDataLock)) { */
int initializeRWLock(RWLock * lock)
{
    return pthread_rwlock_init(lock, NULL);
}

int thread_return(int retval)
{
    pthread_exit(NULL);
}

/* TODO: Unsafe assumptions about timespec and tm */
int thread_sleep(int ms)
{
    pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
    pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
    struct timeval now;
    struct timespec then;
    int deltams;

/*  logFmsg(0,"thread_sleep: called [tid: 0x%x] [ms: %d]", pthread_self(), ms); */
    gettimeofday(&now, NULL);

    deltams = (now.tv_usec / 1000) + ms;

    then.tv_sec = now.tv_sec + (deltams / 1000);
    then.tv_nsec = (deltams % 1000) * 1000000;

    pthread_cond_timedwait(&cond, &mut, (struct timespec *) &then);

    return 0;
}
