00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011 #include "SurcoucheMultitache.h"
00012
00013
00014 int ThreadStart(THREAD *pThread, ROUTINE Process, PARAMETRE Param)
00015 {
00016 #ifdef WIN32
00017 *pThread = (THREAD)CreateThread(NULL, 0, (ROUTINE)Process, (PARAMETRE)Param, 0, NULL);
00018 if(pThread == INVALID_HANDLE_VALUE)
00019 return 1;
00020 #else
00021 pthread_attr_t Type;
00022
00023 if(pthread_attr_init(&Type))
00024 return(1);
00025
00026 pthread_attr_setdetachstate(&Type, PTHREAD_CREATE_JOINABLE);
00027
00028 if(pthread_create((THREAD *)pThread, &Type, (ROUTINE)Process, (PARAMETRE)Param))
00029 return 1;
00030 #endif
00031
00032 return 0;
00033 }
00034
00035 void ThreadStop(THREAD *pThread)
00036 {
00037 #ifdef WIN32
00038 TerminateThread((THREAD)pThread, FALSE);
00039 CloseHandle((THREAD)pThread);
00040 #else
00041 pthread_cancel((THREAD)pThread);
00042 #endif
00043 *pThread = 0;
00044 }
00045
00046 void ThreadExit(int ExitCode)
00047 {
00048 #ifdef WIN32
00049 ExitThread(ExitCode);
00050 #else
00051 pthread_exit((void *)&ExitCode);
00052 #endif
00053 }
00054
00055 void ThreadWait(THREAD *pThread)
00056 {
00057 #ifdef WIN32
00058 WaitForSingleObject((THREAD)pThread, INFINITE);
00059 CloseHandle((THREAD)pThread);
00060 #else
00061 pthread_join((THREAD)*pThread, NULL);
00062 #endif
00063 pThread = NULL;
00064 }
00065
00066 unsigned int ThreadId()
00067 {
00068 #ifdef WIN32
00069 return GetCurrentThreadId();
00070 #else
00071 unsigned int id = 0;
00072
00073 memcpy(&id, (void*)(pthread_self() + 72), sizeof(pid_t));
00074 return id - 1;
00075 #endif
00076 }
00077
00078 void MutexInit(MUTEX *pMutex)
00079 {
00080 #ifdef WIN32
00081 *pMutex = (MUTEX)CreateMutex(NULL, FALSE, NULL);
00082 #else
00083 pthread_mutex_init((MUTEX *)pMutex, NULL);
00084 #endif
00085 }
00086
00087 void MutexLock(MUTEX *pMutex)
00088 {
00089 if(!pMutex)
00090 MutexInit(pMutex);
00091
00092 #ifdef WIN32
00093 WaitForSingleObject((MUTEX)pMutex, INFINITE);
00094 #else
00095 pthread_mutex_lock((MUTEX *)pMutex);
00096 #endif
00097 }
00098
00099 void MutexUnLock(MUTEX *pMutex)
00100 {
00101 #ifdef WIN32
00102 ReleaseMutex((MUTEX)pMutex);
00103 #else
00104 pthread_mutex_unlock((MUTEX *)pMutex);
00105 #endif
00106 }
00107
00108 void MutexStop(MUTEX *pMutex)
00109 {
00110 #ifdef WIN32
00111 ReleaseMutex((MUTEX)pMutex);
00112 CloseHandle((MUTEX)pMutex);
00113 *pMutex = NULL;
00114 #else
00115 pthread_mutex_destroy((MUTEX *)pMutex);
00116 pMutex = NULL;
00117 #endif
00118 }