00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024 #ifndef __LS_THREAD_H__
00025 #define __LS_THREAD_H__
00026
00027
00028 #if defined(WIN32)
00029 #define WIN32_SIGNALSTARTTHREAD_WORKAROUND 1
00030 #endif
00031
00032 #include <iostream>
00033 #include <stdio.h>
00034 #include <stdlib.h>
00035
00036 #if defined(WIN32)
00037 #include <windows.h>
00038 #else
00039 #include <sched.h>
00040 #include <sys/mman.h>
00041 #include <memory.h>
00042 #include <pthread.h>
00043 #endif
00044 #include <errno.h>
00045
00046 #include "Condition.h"
00047
00048 namespace LinuxSampler {
00049
00051 class Thread {
00052 public:
00053 Thread(bool LockMemory, bool RealTime, int PriorityMax, int PriorityDelta);
00054 virtual ~Thread();
00055 virtual int StartThread();
00056 virtual int StopThread();
00057 virtual int SignalStartThread();
00058 virtual int SignalStopThread();
00059
00060 inline void TestCancel() {
00061 #if CONFIG_PTHREAD_TESTCANCEL
00062 pthread_testcancel();
00063 #endif
00064 }
00065
00066 virtual bool IsRunning();
00067 virtual int SetSchedulingPriority();
00068 virtual int LockMemory();
00069 virtual void EnableDestructor();
00070 virtual int Destructor();
00071 virtual int Main() = 0;
00072
00083 static void* allocAlignedMem(size_t boundary, size_t size) {
00084 unsigned char *ptr = (unsigned char *)malloc(size+boundary);
00085 size_t offset = boundary - ((size_t)ptr % boundary);
00086 ptr[offset-1] = (unsigned char)offset;
00087 return (ptr + offset);
00088 }
00089
00095 static void freeAlignedMem(void *ptr) {
00096 unsigned char *p = (unsigned char *)ptr;
00097 p -= p[-1];
00098 free(p);
00099 }
00100
00108 static bool lockMemory(void *addr, size_t size) {
00109 #if defined(WIN32)
00110 return VirtualLock(addr, size);
00111 #else
00112 return !mlock(addr, size);
00113 #endif
00114 }
00115
00123 static bool unlockMemory(void *addr, size_t size) {
00124 #if defined(WIN32)
00125 return VirtualUnlock(addr, size);
00126 #else
00127 return !munlock(addr, size);
00128 #endif
00129 }
00130
00131 private:
00132 #if defined(WIN32)
00133 HANDLE hThread;
00134 DWORD lpThreadId;
00135 #if defined(WIN32_SIGNALSTARTTHREAD_WORKAROUND)
00136 bool win32isRunning;
00137 #endif
00138 #else
00139 pthread_attr_t __thread_attr;
00140 pthread_t __thread_id;
00141 pthread_key_t __thread_destructor_key;
00142 #endif
00143 Condition RunningCondition;
00144 int PriorityMax;
00145 int PriorityDelta;
00146 bool isRealTime;
00147 bool bLockedMemory;
00148 };
00149
00150 }
00151
00152 #endif // __LS_THREAD_H__