/*
//
//   ADOBE SYSTEMS INCORPORATED
//   Copyright (C) 2000-2003 Adobe Systems Incorporated
//   All rights reserved.
//
//   NOTICE: Adobe permits you to use, modify, and distribute this file
//   in accordance with the terms of the Adobe license agreement
//   accompanying it. If you have received this file from a source other
//   than Adobe, then your use, modification, or distribution of it
//   requires the prior written permission of Adobe.
//
*/
#ifndef SDKTHREADS_H
#define SDKTHREADS_H

#ifdef WIN_PLATFORM
#include "windows.h"
#include "process.h"

typedef  HANDLE  SDKThreadID;
#define ThreadFuncReturnType unsigned int WINAPI
typedef  LPVOID  ThreadFuncArgType;
typedef   ThreadFuncReturnType   ThreadFuncType(  ThreadFuncArgType  );
#define createThread( func, pargs, tinfo ) ((tinfo.threadID = (SDKThreadID)_beginthreadex( \
               NULL, 0, (ThreadFuncType *)(&func), (tinfo.threadArgs = pargs), 0, NULL)) != 0)
#define destroyThread( tinfo ) CloseHandle( tinfo.threadID )
#define waitThread( tinfo ) do { \
               DWORD exitCode; \
               GetExitCodeThread( tinfo.threadID, &exitCode ); \
               if (exitCode != STILL_ACTIVE) break; \
               Sleep(0); \
               } while (1);

typedef  CRITICAL_SECTION  CSMutex;
#define EnterCS( CSMutex ) EnterCriticalSection( &CSMutex )
#define LeaveCS( CSMutex ) LeaveCriticalSection( &CSMutex )
#define InitCS( CSMutex ) InitializeCriticalSection( &CSMutex )
#define DestroyCS( CSMutex ) DeleteCriticalSection( &CSMutex )

#else
#include <pthread.h>
#include <unistd.h>

typedef  pthread_t  SDKThreadID;
typedef   void  *  ThreadFuncReturnType;
typedef   void  *  ThreadFuncArgType;
typedef   ThreadFuncReturnType   ThreadFuncType(  ThreadFuncArgType  );
#define createThread( func, pargs, tinfo ) (pthread_create( &tinfo.threadID, NULL, (ThreadFuncType *)func, (tinfo.threadArgs = pargs) ) == 0)

// #define createThread( func, args, ptid ) (pthread_create( ptid, NULL, func, args ) == 0)
#define destroyThread( tinfo ) pthread_detach( tinfo.threadID )
#define waitThread( tinfo ) pthread_join( tinfo.threadID, NULL )
#define Sleep( n ) sleep( n==0?1:n )

typedef  pthread_mutex_t *CSMutex;
#define InitCS( CSMutex ) do { \
               CSMutex = (pthread_mutex_t *)malloc( sizeof(pthread_mutex_t) ); \
               pthread_mutex_init( CSMutex, NULL ); \
               } while (0)

#define EnterCS( CSMutex ) pthread_mutex_lock( CSMutex )
#define LeaveCS( CSMutex ) pthread_mutex_unlock( CSMutex )
#define DestroyCS( CSMutex ) do { \
               pthread_mutex_destroy( CSMutex ); \
               free( CSMutex ); \
               } while (0)

#endif

typedef   struct  {
                SDKThreadID  threadID;
                struct  ThreadArgs  *threadArgs;
               }  ThreadInfo;

#endif //SDKTHREADS_H