systhrd.inc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. {
  2. This file is part of the Free Pascal run time library.
  3. Copyright (c) 2002 by Peter Vreman,
  4. member of the Free Pascal development team.
  5. Linux (pthreads) threading support implementation
  6. See the file COPYING.FPC, included in this distribution,
  7. for details about the copyright.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  11. **********************************************************************}
  12. {*****************************************************************************
  13. Local WINApi imports
  14. *****************************************************************************}
  15. const
  16. { LocalAlloc flags }
  17. LMEM_FIXED = 0;
  18. LMEM_ZEROINIT = 64;
  19. {$ifndef WINCE}
  20. function TlsAlloc : DWord;
  21. stdcall;external KernelDLL name 'TlsAlloc';
  22. function TlsFree(dwTlsIndex : DWord) : LongBool;
  23. stdcall;external KernelDLL name 'TlsFree';
  24. {$endif WINCE}
  25. function TlsGetValue(dwTlsIndex : DWord) : pointer;
  26. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'TlsGetValue';
  27. function TlsSetValue(dwTlsIndex : DWord;lpTlsValue : pointer) : LongBool;
  28. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'TlsSetValue';
  29. function CreateThread(lpThreadAttributes : pointer;
  30. dwStackSize : SIZE_T; lpStartAddress : pointer;lpParameter : pointer;
  31. dwCreationFlags : DWord;var lpThreadId : DWord) : THandle;
  32. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'CreateThread';
  33. procedure ExitThread(dwExitCode : DWord);
  34. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'ExitThread';
  35. function LocalAlloc(uFlags:DWord; dwBytes:DWORD):Pointer;
  36. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'LocalAlloc';
  37. function LocalFree(hMem : Pointer):Pointer; {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'LocalFree';
  38. procedure Sleep(dwMilliseconds: DWord); {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'Sleep';
  39. function WinSuspendThread (threadHandle : THandle) : dword; {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'SuspendThread';
  40. function WinResumeThread (threadHandle : THandle) : dword; {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'ResumeThread';
  41. function TerminateThread (threadHandle : THandle; var exitCode : dword) : boolean; {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'TerminateThread';
  42. function WaitForSingleObject (hHandle : THandle;Milliseconds: dword): dword; {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'WaitForSingleObject';
  43. function WinThreadSetPriority (threadHandle : THandle; Prio: longint): boolean; {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'SetThreadPriority';
  44. function WinThreadGetPriority (threadHandle : THandle): LongInt; {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'GetThreadPriority';
  45. {$ifndef WINCE}
  46. function CreateEvent(lpEventAttributes:pointer;bManualReset:longbool;bInitialState:longbool;lpName:pchar): THandle; stdcall; external KernelDLL name 'CreateEventA';
  47. function ResetEvent(hEvent:THandle):LONGBOOL; stdcall; external KernelDLL name 'ResetEvent';
  48. function SetEvent(hEvent:THandle):LONGBOOL; stdcall; external KernelDLL name 'SetEvent';
  49. {$endif WINCE}
  50. CONST
  51. WAIT_OBJECT_0 = 0;
  52. WAIT_ABANDONED_0 = $80;
  53. WAIT_TIMEOUT = $102;
  54. WAIT_IO_COMPLETION = $c0;
  55. WAIT_ABANDONED = $80;
  56. WAIT_FAILED = $ffffffff;
  57. {*****************************************************************************
  58. Threadvar support
  59. *****************************************************************************}
  60. const
  61. threadvarblocksize : dword = 0;
  62. var
  63. TLSKey : Dword;
  64. procedure SysInitThreadvar(var offset : dword;size : dword);
  65. begin
  66. offset:=threadvarblocksize;
  67. {$ifdef CPUARM}
  68. // Data must be allocated at 4 bytes boundary for ARM
  69. size:=(size + 3) and not dword(3);
  70. {$endif CPUARM}
  71. inc(threadvarblocksize,size);
  72. end;
  73. procedure SysAllocateThreadVars;
  74. var
  75. dataindex : pointer;
  76. begin
  77. { we've to allocate the memory from system }
  78. { because the FPC heap management uses }
  79. { exceptions which use threadvars but }
  80. { these aren't allocated yet ... }
  81. { allocate room on the heap for the thread vars }
  82. dataindex:=pointer(LocalAlloc(LMEM_FIXED or LMEM_ZEROINIT,threadvarblocksize));
  83. TlsSetValue(tlskey,dataindex);
  84. end;
  85. function SysRelocateThreadvar(offset : dword) : pointer;
  86. var
  87. dataindex : pointer;
  88. begin
  89. dataindex := TlsGetValue(tlskey);
  90. if dataindex = nil then begin
  91. SysAllocateThreadVars;
  92. dataindex := TlsGetValue(tlskey);
  93. end;
  94. SysRelocateThreadvar:=DataIndex+Offset;
  95. {
  96. begin
  97. SysRelocateThreadvar:=TlsGetValue(tlskey)+Offset;
  98. } end;
  99. procedure SysReleaseThreadVars;
  100. begin
  101. LocalFree(TlsGetValue(tlskey));
  102. end;
  103. {*****************************************************************************
  104. Thread starting
  105. *****************************************************************************}
  106. type
  107. pthreadinfo = ^tthreadinfo;
  108. tthreadinfo = record
  109. f : tthreadfunc;
  110. p : pointer;
  111. stklen : cardinal;
  112. end;
  113. procedure DoneThread;
  114. begin
  115. { Release Threadvars }
  116. SysReleaseThreadVars;
  117. end;
  118. function ThreadMain(param : pointer) : Longint; {$ifdef wince}cdecl{$else}stdcall{$endif};
  119. var
  120. ti : tthreadinfo;
  121. begin
  122. { Allocate local thread vars, this must be the first thing,
  123. because the exception management and io depends on threadvars }
  124. SysAllocateThreadVars;
  125. { Copy parameter to local data }
  126. {$ifdef DEBUG_MT}
  127. writeln('New thread started, initialising ...');
  128. {$endif DEBUG_MT}
  129. ti:=pthreadinfo(param)^;
  130. dispose(pthreadinfo(param));
  131. { Initialize thread }
  132. InitThread(ti.stklen);
  133. { Start thread function }
  134. {$ifdef DEBUG_MT}
  135. writeln('Jumping to thread function');
  136. {$endif DEBUG_MT}
  137. ThreadMain:=ti.f(ti.p);
  138. end;
  139. function SysBeginThread(sa : Pointer;stacksize : ptruint;
  140. ThreadFunction : tthreadfunc;p : pointer;
  141. creationFlags : dword;var ThreadId : TThreadID) : TThreadID;
  142. var
  143. ti : pthreadinfo;
  144. _threadid : DWord;
  145. begin
  146. {$ifdef DEBUG_MT}
  147. writeln('Creating new thread');
  148. {$endif DEBUG_MT}
  149. { Initialize multithreading if not done }
  150. if not IsMultiThread then
  151. begin
  152. { We're still running in single thread mode, setup the TLS }
  153. TLSKey:=TlsAlloc;
  154. InitThreadVars(@SysRelocateThreadvar);
  155. IsMultiThread:=true;
  156. end;
  157. { the only way to pass data to the newly created thread
  158. in a MT safe way, is to use the heap }
  159. new(ti);
  160. ti^.f:=ThreadFunction;
  161. ti^.p:=p;
  162. ti^.stklen:=stacksize;
  163. { call pthread_create }
  164. {$ifdef DEBUG_MT}
  165. writeln('Starting new thread');
  166. {$endif DEBUG_MT}
  167. _threadid:=ThreadID;
  168. SysBeginThread:=CreateThread(sa,stacksize,@ThreadMain,ti,creationflags,_threadid);
  169. ThreadID:=_threadid;
  170. end;
  171. procedure SysEndThread(ExitCode : DWord);
  172. begin
  173. DoneThread;
  174. ExitThread(ExitCode);
  175. end;
  176. procedure SysThreadSwitch;
  177. begin
  178. Sleep(0);
  179. end;
  180. function SysSuspendThread (threadHandle : TThreadID) : dword;
  181. begin
  182. SysSuspendThread:=WinSuspendThread(threadHandle);
  183. end;
  184. function SysResumeThread (threadHandle : TThreadID) : dword;
  185. begin
  186. SysResumeThread:=WinResumeThread(threadHandle);
  187. end;
  188. function SysKillThread (threadHandle : TThreadID) : dword;
  189. var exitCode : dword;
  190. begin
  191. if not TerminateThread (threadHandle, exitCode) then
  192. SysKillThread := GetLastError
  193. else
  194. SysKillThread := 0;
  195. end;
  196. function SysWaitForThreadTerminate (threadHandle : TThreadID; TimeoutMs : longint) : dword;
  197. begin
  198. if timeoutMs = 0 then dec (timeoutMs); // $ffffffff is INFINITE
  199. SysWaitForThreadTerminate := WaitForSingleObject(threadHandle, TimeoutMs);
  200. end;
  201. function SysThreadSetPriority (threadHandle : TThreadID; Prio: longint): boolean; {-15..+15, 0=normal}
  202. begin
  203. SysThreadSetPriority:=WinThreadSetPriority(threadHandle,Prio);
  204. end;
  205. function SysThreadGetPriority (threadHandle : TThreadID): longint;
  206. begin
  207. SysThreadGetPriority:=WinThreadGetPriority(threadHandle);
  208. end;
  209. function SysGetCurrentThreadId : TThreadID;
  210. begin
  211. SysGetCurrentThreadId:=Win32GetCurrentThreadId;
  212. end;
  213. {*****************************************************************************
  214. Delphi/Win32 compatibility
  215. *****************************************************************************}
  216. procedure WinInitCriticalSection(var cs : TRTLCriticalSection);
  217. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'InitializeCriticalSection';
  218. procedure WinDoneCriticalSection(var cs : TRTLCriticalSection);
  219. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'DeleteCriticalSection';
  220. procedure WinEnterCriticalSection(var cs : TRTLCriticalSection);
  221. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'EnterCriticalSection';
  222. procedure WinLeaveCriticalSection(var cs : TRTLCriticalSection);
  223. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'LeaveCriticalSection';
  224. procedure SySInitCriticalSection(var cs);
  225. begin
  226. WinInitCriticalSection(PRTLCriticalSection(@cs)^);
  227. end;
  228. procedure SysDoneCriticalSection(var cs);
  229. begin
  230. WinDoneCriticalSection(PRTLCriticalSection(@cs)^);
  231. end;
  232. procedure SysEnterCriticalSection(var cs);
  233. begin
  234. WinEnterCriticalSection(PRTLCriticalSection(@cs)^);
  235. end;
  236. procedure SySLeaveCriticalSection(var cs);
  237. begin
  238. WinLeaveCriticalSection(PRTLCriticalSection(@cs)^);
  239. end;
  240. {*****************************************************************************
  241. Heap Mutex Protection
  242. *****************************************************************************}
  243. {$ifndef HAS_MT_MEMORYMANAGER}
  244. var
  245. HeapMutex : TRTLCriticalSection;
  246. procedure Win32HeapMutexInit;
  247. begin
  248. InitCriticalSection(heapmutex);
  249. end;
  250. procedure Win32HeapMutexDone;
  251. begin
  252. DoneCriticalSection(heapmutex);
  253. end;
  254. procedure Win32HeapMutexLock;
  255. begin
  256. EnterCriticalSection(heapmutex);
  257. end;
  258. procedure Win32HeapMutexUnlock;
  259. begin
  260. LeaveCriticalSection(heapmutex);
  261. end;
  262. const
  263. Win32MemoryMutexManager : TMemoryMutexManager = (
  264. MutexInit : @Win32HeapMutexInit;
  265. MutexDone : @Win32HeapMutexDone;
  266. MutexLock : @Win32HeapMutexLock;
  267. MutexUnlock : @Win32HeapMutexUnlock;
  268. );
  269. procedure InitHeapMutexes;
  270. begin
  271. SetMemoryMutexManager(Win32MemoryMutexManager);
  272. end;
  273. {$endif HAS_MT_MEMORYMANAGER}
  274. Const
  275. wrSignaled = 0;
  276. wrTimeout = 1;
  277. wrAbandoned= 2;
  278. wrError = 3;
  279. type Tbasiceventstate=record
  280. fhandle : THandle;
  281. flasterror : longint;
  282. end;
  283. plocaleventrec= ^tbasiceventstate;
  284. function intBasicEventCreate(EventAttributes : Pointer;
  285. AManualReset,InitialState : Boolean;const Name : ansistring):pEventState;
  286. begin
  287. new(plocaleventrec(result));
  288. plocaleventrec(result)^.FHandle := CreateEvent(EventAttributes, AManualReset, InitialState,PChar(Name));
  289. end;
  290. procedure intbasiceventdestroy(state:peventstate);
  291. begin
  292. closehandle(plocaleventrec(state)^.fhandle);
  293. dispose(plocaleventrec(state));
  294. end;
  295. procedure intbasiceventResetEvent(state:peventstate);
  296. begin
  297. ResetEvent(plocaleventrec(state)^.FHandle)
  298. end;
  299. procedure intbasiceventSetEvent(state:peventstate);
  300. begin
  301. SetEvent(plocaleventrec(state)^.FHandle);
  302. end;
  303. function intbasiceventWaitFor(Timeout : Cardinal;state:peventstate) : longint;
  304. begin
  305. case WaitForSingleObject(plocaleventrec(state)^.fHandle, Timeout) of
  306. WAIT_ABANDONED: Result := wrAbandoned;
  307. WAIT_OBJECT_0: Result := wrSignaled;
  308. WAIT_TIMEOUT: Result := wrTimeout;
  309. WAIT_FAILED:
  310. begin
  311. Result := wrError;
  312. plocaleventrec(state)^.FLastError := GetLastError;
  313. end;
  314. else
  315. Result := wrError;
  316. end;
  317. end;
  318. function intRTLEventCreate: PRTLEvent;
  319. begin
  320. Result := PRTLEVENT(CreateEvent(nil, false, false, nil));
  321. end;
  322. procedure intRTLEventDestroy(AEvent: PRTLEvent);
  323. begin
  324. CloseHandle(THANDLE(AEvent));
  325. end;
  326. procedure intRTLEventSetEvent(AEvent: PRTLEvent);
  327. begin
  328. SetEvent(THANDLE(AEvent));
  329. end;
  330. procedure intRTLEventResetEvent(AEvent: PRTLEvent);
  331. begin
  332. ResetEvent(THANDLE(AEvent));
  333. end;
  334. procedure intRTLEventWaitFor(AEvent: PRTLEvent);
  335. const
  336. INFINITE=dword(-1);
  337. begin
  338. WaitForSingleObject(THANDLE(AEvent), INFINITE);
  339. end;
  340. procedure intRTLEventWaitForTimeout(AEvent: PRTLEvent;timeout : longint);
  341. begin
  342. WaitForSingleObject(THANDLE(AEvent), timeout);
  343. end;
  344. Var
  345. WinThreadManager : TThreadManager;
  346. Procedure InitSystemThreads;
  347. begin
  348. With WinThreadManager do
  349. begin
  350. InitManager :=Nil;
  351. DoneManager :=Nil;
  352. BeginThread :=@SysBeginThread;
  353. EndThread :=@SysEndThread;
  354. SuspendThread :=@SysSuspendThread;
  355. ResumeThread :=@SysResumeThread;
  356. KillThread :=@SysKillThread;
  357. ThreadSwitch :=@SysThreadSwitch;
  358. WaitForThreadTerminate :=@SysWaitForThreadTerminate;
  359. ThreadSetPriority :=@SysThreadSetPriority;
  360. ThreadGetPriority :=@SysThreadGetPriority;
  361. GetCurrentThreadId :=@SysGetCurrentThreadId;
  362. InitCriticalSection :=@SysInitCriticalSection;
  363. DoneCriticalSection :=@SysDoneCriticalSection;
  364. EnterCriticalSection :=@SysEnterCriticalSection;
  365. LeaveCriticalSection :=@SysLeaveCriticalSection;
  366. InitThreadVar :=@SysInitThreadVar;
  367. RelocateThreadVar :=@SysRelocateThreadVar;
  368. AllocateThreadVars :=@SysAllocateThreadVars;
  369. ReleaseThreadVars :=@SysReleaseThreadVars;
  370. BasicEventCreate :=@intBasicEventCreate;
  371. BasicEventDestroy :=@intBasicEventDestroy;
  372. BasicEventResetEvent :=@intBasicEventResetEvent;
  373. BasicEventSetEvent :=@intBasicEventSetEvent;
  374. BasiceventWaitFor :=@intBasiceventWaitFor;
  375. RTLEventCreate :=@intRTLEventCreate;
  376. RTLEventDestroy :=@intRTLEventDestroy;
  377. RTLEventSetEvent :=@intRTLEventSetEvent;
  378. RTLEventResetEvent :=@intRTLEventResetEvent;
  379. RTLEventWaitFor :=@intRTLEventWaitFor;
  380. RTLEventWaitForTimeout :=@intRTLEventWaitForTimeout;
  381. end;
  382. SetThreadManager(WinThreadManager);
  383. {$ifndef HAS_MT_MEMORYMANAGER}
  384. InitHeapMutexes;
  385. {$endif HAS_MT_MEMORYMANAGER}
  386. ThreadID := GetCurrentThreadID;
  387. end;