systhrd.inc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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. errorsave : dword;
  89. begin
  90. {$ifdef dummy}
  91. { I've no clue why this doesn't read dataindex, imo it should (FK) }
  92. asm
  93. movl TLSKey,%edx
  94. movl $0x2c,%eax
  95. movl %fs:(%eax),%eax
  96. movl (%eax,%edx,4),%eax
  97. movl %eax,dataindex
  98. end;
  99. if DataIndex=nil then
  100. begin
  101. errorsave:=GetLastError;
  102. SysAllocateThreadVars;
  103. DataIndex:=TlsGetValue(tlskey);
  104. SetLastError(errorsave);
  105. end;
  106. {$else win32}
  107. errorsave:=GetLastError;
  108. dataindex:=TlsGetValue(tlskey);
  109. if dataindex=nil then
  110. begin
  111. SysAllocateThreadVars;
  112. dataindex:=TlsGetValue(tlskey);
  113. end;
  114. SetLastError(errorsave);
  115. {$endif win32}
  116. SysRelocateThreadvar:=DataIndex+Offset;
  117. end;
  118. procedure SysReleaseThreadVars;
  119. begin
  120. LocalFree(TlsGetValue(tlskey));
  121. TlsSetValue(tlskey, nil);
  122. end;
  123. {*****************************************************************************
  124. Thread starting
  125. *****************************************************************************}
  126. type
  127. pthreadinfo = ^tthreadinfo;
  128. tthreadinfo = record
  129. f : tthreadfunc;
  130. p : pointer;
  131. stklen : cardinal;
  132. end;
  133. function ThreadMain(param : pointer) : Longint; {$ifdef wince}cdecl{$else}stdcall{$endif};
  134. var
  135. ti : tthreadinfo;
  136. begin
  137. { Allocate local thread vars, this must be the first thing,
  138. because the exception management and io depends on threadvars }
  139. SysAllocateThreadVars;
  140. { Copy parameter to local data }
  141. ti:=pthreadinfo(param)^;
  142. dispose(pthreadinfo(param));
  143. { Initialize thread }
  144. InitThread(ti.stklen);
  145. { Start thread function }
  146. {$ifdef DEBUG_MT}
  147. writeln('Jumping to thread function of thread ',Win32GetCurrentThreadId);
  148. {$endif DEBUG_MT}
  149. ThreadMain:=ti.f(ti.p);
  150. end;
  151. procedure SysInitMultithreading;
  152. begin
  153. { do not check IsMultiThread, as program could have altered it, out of Delphi habit }
  154. if TLSKey = 0 then
  155. begin
  156. { We're still running in single thread mode, setup the TLS }
  157. TLSKey:=TlsAlloc;
  158. InitThreadVars(@SysRelocateThreadvar);
  159. IsMultiThread:=true;
  160. end;
  161. end;
  162. procedure SysFiniMultithreading;
  163. begin
  164. if IsMultiThread then
  165. begin
  166. TlsFree(TLSKey);
  167. TLSKey := 0;
  168. end;
  169. end;
  170. function SysBeginThread(sa : Pointer;stacksize : ptruint;
  171. ThreadFunction : tthreadfunc;p : pointer;
  172. creationFlags : dword;var ThreadId : TThreadID) : TThreadID;
  173. var
  174. ti : pthreadinfo;
  175. _threadid : dword;
  176. begin
  177. {$ifdef DEBUG_MT}
  178. writeln('Creating new thread');
  179. {$endif DEBUG_MT}
  180. { Initialize multithreading if not done }
  181. SysInitMultithreading;
  182. { the only way to pass data to the newly created thread
  183. in a MT safe way, is to use the heap }
  184. new(ti);
  185. ti^.f:=ThreadFunction;
  186. ti^.p:=p;
  187. ti^.stklen:=stacksize;
  188. {$ifdef DEBUG_MT}
  189. writeln('Starting new thread');
  190. {$endif DEBUG_MT}
  191. _threadid:=0;
  192. SysBeginThread:=CreateThread(sa,stacksize,@ThreadMain,ti,creationflags,_threadid);
  193. { creation failed? if yes, we dispose the parameter record }
  194. if SysBeginThread=0 then
  195. begin
  196. {$ifdef DEBUG_MT}
  197. writeln('Thread creation failed');
  198. {$endif DEBUG_MT}
  199. dispose(ti);
  200. end;
  201. ThreadID:=_threadid;
  202. end;
  203. procedure SysEndThread(ExitCode : DWord);
  204. begin
  205. DoneThread;
  206. ExitThread(ExitCode);
  207. end;
  208. procedure SysThreadSwitch;
  209. begin
  210. Sleep(0);
  211. end;
  212. function SysSuspendThread (threadHandle : TThreadID) : dword;
  213. begin
  214. SysSuspendThread:=WinSuspendThread(threadHandle);
  215. end;
  216. function SysResumeThread (threadHandle : TThreadID) : dword;
  217. begin
  218. SysResumeThread:=WinResumeThread(threadHandle);
  219. end;
  220. function SysKillThread (threadHandle : TThreadID) : dword;
  221. var exitCode : dword;
  222. begin
  223. if not TerminateThread (threadHandle, exitCode) then
  224. SysKillThread := GetLastError
  225. else
  226. SysKillThread := 0;
  227. end;
  228. function SysWaitForThreadTerminate (threadHandle : TThreadID; TimeoutMs : longint) : dword;
  229. begin
  230. if timeoutMs = 0 then dec (timeoutMs); // $ffffffff is INFINITE
  231. SysWaitForThreadTerminate := WaitForSingleObject(threadHandle, TimeoutMs);
  232. end;
  233. function SysThreadSetPriority (threadHandle : TThreadID; Prio: longint): boolean; {-15..+15, 0=normal}
  234. begin
  235. SysThreadSetPriority:=WinThreadSetPriority(threadHandle,Prio);
  236. end;
  237. function SysThreadGetPriority (threadHandle : TThreadID): longint;
  238. begin
  239. SysThreadGetPriority:=WinThreadGetPriority(threadHandle);
  240. end;
  241. function SysGetCurrentThreadId : TThreadID;
  242. begin
  243. SysGetCurrentThreadId:=Win32GetCurrentThreadId;
  244. end;
  245. {*****************************************************************************
  246. Delphi/Win32 compatibility
  247. *****************************************************************************}
  248. procedure WinInitCriticalSection(var cs : TRTLCriticalSection);
  249. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'InitializeCriticalSection';
  250. procedure WinDoneCriticalSection(var cs : TRTLCriticalSection);
  251. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'DeleteCriticalSection';
  252. procedure WinEnterCriticalSection(var cs : TRTLCriticalSection);
  253. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'EnterCriticalSection';
  254. procedure WinLeaveCriticalSection(var cs : TRTLCriticalSection);
  255. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'LeaveCriticalSection';
  256. procedure SySInitCriticalSection(var cs);
  257. begin
  258. WinInitCriticalSection(PRTLCriticalSection(@cs)^);
  259. end;
  260. procedure SysDoneCriticalSection(var cs);
  261. begin
  262. WinDoneCriticalSection(PRTLCriticalSection(@cs)^);
  263. end;
  264. procedure SysEnterCriticalSection(var cs);
  265. begin
  266. WinEnterCriticalSection(PRTLCriticalSection(@cs)^);
  267. end;
  268. procedure SySLeaveCriticalSection(var cs);
  269. begin
  270. WinLeaveCriticalSection(PRTLCriticalSection(@cs)^);
  271. end;
  272. Const
  273. wrSignaled = 0;
  274. wrTimeout = 1;
  275. wrAbandoned= 2;
  276. wrError = 3;
  277. type Tbasiceventstate=record
  278. fhandle : THandle;
  279. flasterror : longint;
  280. end;
  281. plocaleventrec= ^tbasiceventstate;
  282. function intBasicEventCreate(EventAttributes : Pointer;
  283. AManualReset,InitialState : Boolean;const Name : ansistring):pEventState;
  284. begin
  285. new(plocaleventrec(result));
  286. plocaleventrec(result)^.FHandle := CreateEvent(EventAttributes, AManualReset, InitialState,PChar(Name));
  287. end;
  288. procedure intbasiceventdestroy(state:peventstate);
  289. begin
  290. closehandle(plocaleventrec(state)^.fhandle);
  291. dispose(plocaleventrec(state));
  292. end;
  293. procedure intbasiceventResetEvent(state:peventstate);
  294. begin
  295. ResetEvent(plocaleventrec(state)^.FHandle)
  296. end;
  297. procedure intbasiceventSetEvent(state:peventstate);
  298. begin
  299. SetEvent(plocaleventrec(state)^.FHandle);
  300. end;
  301. function intbasiceventWaitFor(Timeout : Cardinal;state:peventstate) : longint;
  302. begin
  303. case WaitForSingleObject(plocaleventrec(state)^.fHandle, Timeout) of
  304. WAIT_ABANDONED: Result := wrAbandoned;
  305. WAIT_OBJECT_0: Result := wrSignaled;
  306. WAIT_TIMEOUT: Result := wrTimeout;
  307. WAIT_FAILED:
  308. begin
  309. Result := wrError;
  310. plocaleventrec(state)^.FLastError := GetLastError;
  311. end;
  312. else
  313. Result := wrError;
  314. end;
  315. end;
  316. function intRTLEventCreate: PRTLEvent;
  317. begin
  318. Result := PRTLEVENT(CreateEvent(nil, false, false, nil));
  319. end;
  320. procedure intRTLEventDestroy(AEvent: PRTLEvent);
  321. begin
  322. CloseHandle(THANDLE(AEvent));
  323. end;
  324. procedure intRTLEventSetEvent(AEvent: PRTLEvent);
  325. begin
  326. SetEvent(THANDLE(AEvent));
  327. end;
  328. procedure intRTLEventResetEvent(AEvent: PRTLEvent);
  329. begin
  330. ResetEvent(THANDLE(AEvent));
  331. end;
  332. procedure intRTLEventWaitFor(AEvent: PRTLEvent);
  333. const
  334. INFINITE=dword(-1);
  335. begin
  336. WaitForSingleObject(THANDLE(AEvent), INFINITE);
  337. end;
  338. procedure intRTLEventWaitForTimeout(AEvent: PRTLEvent;timeout : longint);
  339. begin
  340. WaitForSingleObject(THANDLE(AEvent), timeout);
  341. end;
  342. Var
  343. WinThreadManager : TThreadManager;
  344. Procedure InitSystemThreads;
  345. begin
  346. With WinThreadManager do
  347. begin
  348. InitManager :=Nil;
  349. DoneManager :=Nil;
  350. BeginThread :=@SysBeginThread;
  351. EndThread :=@SysEndThread;
  352. SuspendThread :=@SysSuspendThread;
  353. ResumeThread :=@SysResumeThread;
  354. KillThread :=@SysKillThread;
  355. ThreadSwitch :=@SysThreadSwitch;
  356. WaitForThreadTerminate :=@SysWaitForThreadTerminate;
  357. ThreadSetPriority :=@SysThreadSetPriority;
  358. ThreadGetPriority :=@SysThreadGetPriority;
  359. GetCurrentThreadId :=@SysGetCurrentThreadId;
  360. InitCriticalSection :=@SysInitCriticalSection;
  361. DoneCriticalSection :=@SysDoneCriticalSection;
  362. EnterCriticalSection :=@SysEnterCriticalSection;
  363. LeaveCriticalSection :=@SysLeaveCriticalSection;
  364. InitThreadVar :=@SysInitThreadVar;
  365. RelocateThreadVar :=@SysRelocateThreadVar;
  366. AllocateThreadVars :=@SysAllocateThreadVars;
  367. ReleaseThreadVars :=@SysReleaseThreadVars;
  368. BasicEventCreate :=@intBasicEventCreate;
  369. BasicEventDestroy :=@intBasicEventDestroy;
  370. BasicEventResetEvent :=@intBasicEventResetEvent;
  371. BasicEventSetEvent :=@intBasicEventSetEvent;
  372. BasiceventWaitFor :=@intBasiceventWaitFor;
  373. RTLEventCreate :=@intRTLEventCreate;
  374. RTLEventDestroy :=@intRTLEventDestroy;
  375. RTLEventSetEvent :=@intRTLEventSetEvent;
  376. RTLEventResetEvent :=@intRTLEventResetEvent;
  377. RTLEventWaitFor :=@intRTLEventWaitFor;
  378. RTLEventWaitForTimeout :=@intRTLEventWaitForTimeout;
  379. end;
  380. SetThreadManager(WinThreadManager);
  381. ThreadID := GetCurrentThreadID;
  382. end;