systhrd.inc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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 WinCloseHandle (threadHandle : THandle) : dword; {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'CloseHandle';
  42. function TerminateThread (threadHandle : THandle; var exitCode : dword) : boolean; {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'TerminateThread';
  43. function WaitForSingleObject (hHandle : THandle;Milliseconds: dword): dword; {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'WaitForSingleObject';
  44. function WinThreadSetPriority (threadHandle : THandle; Prio: longint): boolean; {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'SetThreadPriority';
  45. function WinThreadGetPriority (threadHandle : THandle): LongInt; {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'GetThreadPriority';
  46. {$ifndef WINCE}
  47. function CreateEvent(lpEventAttributes:pointer;bManualReset:longbool;bInitialState:longbool;lpName:pchar): THandle; stdcall; external KernelDLL name 'CreateEventA';
  48. function ResetEvent(hEvent:THandle):LONGBOOL; stdcall; external KernelDLL name 'ResetEvent';
  49. function SetEvent(hEvent:THandle):LONGBOOL; stdcall; external KernelDLL name 'SetEvent';
  50. {$endif WINCE}
  51. procedure WinInitCriticalSection(var cs : TRTLCriticalSection);
  52. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'InitializeCriticalSection';
  53. procedure WinDoneCriticalSection(var cs : TRTLCriticalSection);
  54. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'DeleteCriticalSection';
  55. procedure WinEnterCriticalSection(var cs : TRTLCriticalSection);
  56. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'EnterCriticalSection';
  57. function WinTryEnterCriticalSection(var cs : TRTLCriticalSection):longint;
  58. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'TryEnterCriticalSection';
  59. procedure WinLeaveCriticalSection(var cs : TRTLCriticalSection);
  60. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'LeaveCriticalSection';
  61. CONST
  62. WAIT_OBJECT_0 = 0;
  63. WAIT_ABANDONED_0 = $80;
  64. WAIT_TIMEOUT = $102;
  65. WAIT_IO_COMPLETION = $c0;
  66. WAIT_ABANDONED = $80;
  67. WAIT_FAILED = $ffffffff;
  68. {*****************************************************************************
  69. Threadvar support
  70. *****************************************************************************}
  71. const
  72. threadvarblocksize : dword = 0;
  73. const
  74. TLSKey : DWord = $ffffffff;
  75. var
  76. MainThreadIdWin32 : DWORD;
  77. procedure SysInitThreadvar(var offset : dword;size : dword);
  78. begin
  79. offset:=threadvarblocksize;
  80. {$ifdef CPUARM}
  81. // Data must be allocated at 4 bytes boundary for ARM
  82. size:=(size + 3) and not dword(3);
  83. {$endif CPUARM}
  84. inc(threadvarblocksize,size);
  85. end;
  86. procedure SysAllocateThreadVars;
  87. var
  88. dataindex : pointer;
  89. begin
  90. { we've to allocate the memory from system }
  91. { because the FPC heap management uses }
  92. { exceptions which use threadvars but }
  93. { these aren't allocated yet ... }
  94. { allocate room on the heap for the thread vars }
  95. dataindex:=pointer(LocalAlloc(LMEM_FIXED or LMEM_ZEROINIT,threadvarblocksize));
  96. TlsSetValue(tlskey,dataindex);
  97. end;
  98. function SysRelocateThreadvar(offset : dword) : pointer; forward;
  99. procedure SysInitMultithreading;
  100. begin
  101. { do not check IsMultiThread, as program could have altered it, out of Delphi habit }
  102. { the thread attach/detach code uses locks to avoid multiple calls of this }
  103. if TLSKey=$ffffffff then
  104. begin
  105. { We're still running in single thread mode, setup the TLS }
  106. TLSKey:=TlsAlloc;
  107. InitThreadVars(@SysRelocateThreadvar);
  108. IsMultiThread:=true;
  109. end;
  110. end;
  111. procedure SysFiniMultithreading;
  112. begin
  113. if IsMultiThread then
  114. begin
  115. TlsFree(TLSKey);
  116. TLSKey:=$ffffffff;
  117. end;
  118. end;
  119. function SysRelocateThreadvar(offset : dword) : pointer;
  120. var
  121. dataindex : pointer;
  122. errorsave : dword;
  123. begin
  124. {$ifdef dummy}
  125. { it least in the on windows 7 x64, this still doesn't not work, fs:(0x2c) is
  126. self referencing on this system (FK)
  127. MVC: It also does not work on Windows Vista 32-bit, Home Premium, SP 1. Results in a crash}
  128. asm
  129. movl TLSKey,%edx
  130. movl %fs:(0x2c),%eax
  131. orl %eax,%eax
  132. jnz .LAddressInEAX
  133. { this works on Windows 7, but I don't know if it works on other OSes (FK) }
  134. movl %fs:(0x18),%eax
  135. movl 0xe10(%eax,%edx,4),%eax
  136. jmp .LToDataIndex
  137. .LAddressInEAX:
  138. movl (%eax,%edx,4),%eax
  139. .LToDataIndex:
  140. movl %eax,dataindex
  141. end;
  142. if DataIndex=nil then
  143. begin
  144. errorsave:=GetLastError;
  145. SysAllocateThreadVars;
  146. DataIndex:=TlsGetValue(tlskey);
  147. SetLastError(errorsave);
  148. end;
  149. {$else win32}
  150. errorsave:=GetLastError;
  151. dataindex:=TlsGetValue(tlskey);
  152. if dataindex=nil then
  153. begin
  154. SysAllocateThreadVars;
  155. dataindex:=TlsGetValue(tlskey);
  156. end;
  157. SetLastError(errorsave);
  158. {$endif win32}
  159. SysRelocateThreadvar:=DataIndex+Offset;
  160. end;
  161. procedure SysReleaseThreadVars;
  162. begin
  163. LocalFree(TlsGetValue(tlskey));
  164. TlsSetValue(tlskey, nil);
  165. end;
  166. {*****************************************************************************
  167. Thread starting
  168. *****************************************************************************}
  169. type
  170. pthreadinfo = ^tthreadinfo;
  171. tthreadinfo = record
  172. f : tthreadfunc;
  173. p : pointer;
  174. stklen : cardinal;
  175. end;
  176. function ThreadMain(param : pointer) : Longint; {$ifdef wince}cdecl{$else}stdcall{$endif};
  177. var
  178. ti : tthreadinfo;
  179. begin
  180. { Allocate local thread vars, this must be the first thing,
  181. because the exception management and io depends on threadvars }
  182. SysAllocateThreadVars;
  183. { Copy parameter to local data }
  184. ti:=pthreadinfo(param)^;
  185. dispose(pthreadinfo(param));
  186. { Initialize thread }
  187. InitThread(ti.stklen);
  188. { Start thread function }
  189. {$ifdef DEBUG_MT}
  190. writeln('Jumping to thread function of thread ',Win32GetCurrentThreadId);
  191. {$endif DEBUG_MT}
  192. ThreadMain:=ti.f(ti.p);
  193. end;
  194. function SysBeginThread(sa : Pointer;stacksize : ptruint;
  195. ThreadFunction : tthreadfunc;p : pointer;
  196. creationFlags : dword;var ThreadId : TThreadID) : TThreadID;
  197. var
  198. ti : pthreadinfo;
  199. _threadid : dword;
  200. begin
  201. {$ifdef DEBUG_MT}
  202. writeln('Creating new thread');
  203. {$endif DEBUG_MT}
  204. { Initialize multithreading if not done }
  205. SysInitMultithreading;
  206. { the only way to pass data to the newly created thread
  207. in a MT safe way, is to use the heap }
  208. new(ti);
  209. ti^.f:=ThreadFunction;
  210. ti^.p:=p;
  211. ti^.stklen:=stacksize;
  212. {$ifdef DEBUG_MT}
  213. writeln('Starting new thread');
  214. {$endif DEBUG_MT}
  215. _threadid:=0;
  216. SysBeginThread:=CreateThread(sa,stacksize,@ThreadMain,ti,creationflags,_threadid);
  217. { creation failed? if yes, we dispose the parameter record }
  218. if SysBeginThread=0 then
  219. begin
  220. {$ifdef DEBUG_MT}
  221. writeln('Thread creation failed');
  222. {$endif DEBUG_MT}
  223. dispose(ti);
  224. end;
  225. ThreadID:=_threadid;
  226. end;
  227. procedure SysEndThread(ExitCode : DWord);
  228. begin
  229. DoneThread;
  230. ExitThread(ExitCode);
  231. end;
  232. procedure SysThreadSwitch;
  233. begin
  234. Sleep(0);
  235. end;
  236. function SysSuspendThread (threadHandle : TThreadID) : dword;
  237. begin
  238. SysSuspendThread:=WinSuspendThread(threadHandle);
  239. end;
  240. function SysResumeThread (threadHandle : TThreadID) : dword;
  241. begin
  242. SysResumeThread:=WinResumeThread(threadHandle);
  243. end;
  244. function SysKillThread (threadHandle : TThreadID) : dword;
  245. var exitCode : dword;
  246. begin
  247. if not TerminateThread (threadHandle, exitCode) then
  248. SysKillThread := GetLastError
  249. else
  250. SysKillThread := 0;
  251. end;
  252. function SysCloseThread (threadHandle : TThreadID) : dword;
  253. begin
  254. SysCloseThread:=winCloseHandle(threadHandle);
  255. end;
  256. function SysWaitForThreadTerminate (threadHandle : TThreadID; TimeoutMs : longint) : dword;
  257. begin
  258. if timeoutMs = 0 then dec (timeoutMs); // $ffffffff is INFINITE
  259. SysWaitForThreadTerminate := WaitForSingleObject(threadHandle, TimeoutMs);
  260. end;
  261. function SysThreadSetPriority (threadHandle : TThreadID; Prio: longint): boolean; {-15..+15, 0=normal}
  262. begin
  263. SysThreadSetPriority:=WinThreadSetPriority(threadHandle,Prio);
  264. end;
  265. function SysThreadGetPriority (threadHandle : TThreadID): longint;
  266. begin
  267. SysThreadGetPriority:=WinThreadGetPriority(threadHandle);
  268. end;
  269. function SysGetCurrentThreadId : TThreadID;
  270. begin
  271. SysGetCurrentThreadId:=Win32GetCurrentThreadId;
  272. end;
  273. {*****************************************************************************
  274. Delphi/Win32 compatibility
  275. *****************************************************************************}
  276. procedure SySInitCriticalSection(var cs);
  277. begin
  278. WinInitCriticalSection(PRTLCriticalSection(@cs)^);
  279. end;
  280. procedure SysDoneCriticalSection(var cs);
  281. begin
  282. WinDoneCriticalSection(PRTLCriticalSection(@cs)^);
  283. end;
  284. procedure SysEnterCriticalSection(var cs);
  285. begin
  286. WinEnterCriticalSection(PRTLCriticalSection(@cs)^);
  287. end;
  288. function SysTryEnterCriticalSection(var cs):longint;
  289. begin
  290. result:=WinTryEnterCriticalSection(PRTLCriticalSection(@cs)^);
  291. end;
  292. procedure SySLeaveCriticalSection(var cs);
  293. begin
  294. WinLeaveCriticalSection(PRTLCriticalSection(@cs)^);
  295. end;
  296. Const
  297. wrSignaled = 0;
  298. wrTimeout = 1;
  299. wrAbandoned= 2;
  300. wrError = 3;
  301. type Tbasiceventstate=record
  302. fhandle : THandle;
  303. flasterror : longint;
  304. end;
  305. plocaleventrec= ^tbasiceventstate;
  306. function intBasicEventCreate(EventAttributes : Pointer;
  307. AManualReset,InitialState : Boolean;const Name : ansistring):pEventState;
  308. begin
  309. new(plocaleventrec(result));
  310. plocaleventrec(result)^.FHandle := CreateEvent(EventAttributes, AManualReset, InitialState,PChar(Name));
  311. end;
  312. procedure intbasiceventdestroy(state:peventstate);
  313. begin
  314. closehandle(plocaleventrec(state)^.fhandle);
  315. dispose(plocaleventrec(state));
  316. end;
  317. procedure intbasiceventResetEvent(state:peventstate);
  318. begin
  319. ResetEvent(plocaleventrec(state)^.FHandle)
  320. end;
  321. procedure intbasiceventSetEvent(state:peventstate);
  322. begin
  323. SetEvent(plocaleventrec(state)^.FHandle);
  324. end;
  325. function intbasiceventWaitFor(Timeout : Cardinal;state:peventstate) : longint;
  326. begin
  327. case WaitForSingleObject(plocaleventrec(state)^.fHandle, Timeout) of
  328. WAIT_ABANDONED: Result := wrAbandoned;
  329. WAIT_OBJECT_0: Result := wrSignaled;
  330. WAIT_TIMEOUT: Result := wrTimeout;
  331. WAIT_FAILED:
  332. begin
  333. Result := wrError;
  334. plocaleventrec(state)^.FLastError := GetLastError;
  335. end;
  336. else
  337. Result := wrError;
  338. end;
  339. end;
  340. function intRTLEventCreate: PRTLEvent;
  341. begin
  342. Result := PRTLEVENT(CreateEvent(nil, false, false, nil));
  343. end;
  344. procedure intRTLEventDestroy(AEvent: PRTLEvent);
  345. begin
  346. CloseHandle(THANDLE(AEvent));
  347. end;
  348. procedure intRTLEventSetEvent(AEvent: PRTLEvent);
  349. begin
  350. SetEvent(THANDLE(AEvent));
  351. end;
  352. procedure intRTLEventResetEvent(AEvent: PRTLEvent);
  353. begin
  354. ResetEvent(THANDLE(AEvent));
  355. end;
  356. procedure intRTLEventWaitFor(AEvent: PRTLEvent);
  357. const
  358. INFINITE=dword(-1);
  359. begin
  360. WaitForSingleObject(THANDLE(AEvent), INFINITE);
  361. end;
  362. procedure intRTLEventWaitForTimeout(AEvent: PRTLEvent;timeout : longint);
  363. begin
  364. WaitForSingleObject(THANDLE(AEvent), timeout);
  365. end;
  366. Var
  367. WinThreadManager : TThreadManager;
  368. Procedure InitSystemThreads;
  369. begin
  370. With WinThreadManager do
  371. begin
  372. InitManager :=Nil;
  373. DoneManager :=Nil;
  374. BeginThread :=@SysBeginThread;
  375. EndThread :=@SysEndThread;
  376. SuspendThread :=@SysSuspendThread;
  377. ResumeThread :=@SysResumeThread;
  378. KillThread :=@SysKillThread;
  379. ThreadSwitch :=@SysThreadSwitch;
  380. CloseThread :=@SysCloseThread;
  381. WaitForThreadTerminate :=@SysWaitForThreadTerminate;
  382. ThreadSetPriority :=@SysThreadSetPriority;
  383. ThreadGetPriority :=@SysThreadGetPriority;
  384. GetCurrentThreadId :=@SysGetCurrentThreadId;
  385. InitCriticalSection :=@SysInitCriticalSection;
  386. DoneCriticalSection :=@SysDoneCriticalSection;
  387. EnterCriticalSection :=@SysEnterCriticalSection;
  388. TryEnterCriticalSection:=@SysTryEnterCriticalSection;
  389. LeaveCriticalSection :=@SysLeaveCriticalSection;
  390. InitThreadVar :=@SysInitThreadVar;
  391. RelocateThreadVar :=@SysRelocateThreadVar;
  392. AllocateThreadVars :=@SysAllocateThreadVars;
  393. ReleaseThreadVars :=@SysReleaseThreadVars;
  394. BasicEventCreate :=@intBasicEventCreate;
  395. BasicEventDestroy :=@intBasicEventDestroy;
  396. BasicEventResetEvent :=@intBasicEventResetEvent;
  397. BasicEventSetEvent :=@intBasicEventSetEvent;
  398. BasiceventWaitFor :=@intBasiceventWaitFor;
  399. RTLEventCreate :=@intRTLEventCreate;
  400. RTLEventDestroy :=@intRTLEventDestroy;
  401. RTLEventSetEvent :=@intRTLEventSetEvent;
  402. RTLEventResetEvent :=@intRTLEventResetEvent;
  403. RTLEventWaitFor :=@intRTLEventWaitFor;
  404. RTLEventWaitForTimeout :=@intRTLEventWaitForTimeout;
  405. end;
  406. SetThreadManager(WinThreadManager);
  407. ThreadID := GetCurrentThreadID;
  408. if IsLibrary then
  409. SysInitMultithreading;
  410. end;