systhrd.inc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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:SIZE_T):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. procedure WinLeaveCriticalSection(var cs : TRTLCriticalSection);
  58. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'LeaveCriticalSection';
  59. CONST
  60. WAIT_OBJECT_0 = 0;
  61. WAIT_ABANDONED_0 = $80;
  62. WAIT_TIMEOUT = $102;
  63. WAIT_IO_COMPLETION = $c0;
  64. WAIT_ABANDONED = $80;
  65. WAIT_FAILED = $ffffffff;
  66. {$ifndef SUPPORT_WIN95}
  67. function WinTryEnterCriticalSection(var cs : TRTLCriticalSection):longint;
  68. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'TryEnterCriticalSection';
  69. {$else SUPPORT_WIN95}
  70. type
  71. TTryEnterCriticalSection = function(var cs : TRTLCriticalSection):longint; stdcall;
  72. var
  73. WinTryEnterCriticalSection : TTryEnterCriticalSection;
  74. {$endif SUPPORT_WIN95}
  75. {*****************************************************************************
  76. Threadvar support
  77. *****************************************************************************}
  78. var
  79. // public names are used by heaptrc unit
  80. threadvarblocksize : dword; public name '_FPC_TlsSize';
  81. TLSKey : DWord = $ffffffff; public name '_FPC_TlsKey';
  82. var
  83. MainThreadIdWin32 : DWORD;
  84. procedure SysInitThreadvar(var offset : dword;size : dword);
  85. begin
  86. offset:=threadvarblocksize;
  87. {$ifdef CPUARM}
  88. // Data must be allocated at 4 bytes boundary for ARM
  89. size:=(size + 3) and not dword(3);
  90. {$endif CPUARM}
  91. inc(threadvarblocksize,size);
  92. end;
  93. procedure SysAllocateThreadVars; public name '_FPC_SysAllocateThreadVars';
  94. var
  95. dataindex : pointer;
  96. errorsave : dword;
  97. begin
  98. { we've to allocate the memory from system }
  99. { because the FPC heap management uses }
  100. { exceptions which use threadvars but }
  101. { these aren't allocated yet ... }
  102. { allocate room on the heap for the thread vars }
  103. errorsave:=GetLastError;
  104. if tlskey=$ffffffff then
  105. RunError(226);
  106. dataindex:=TlsGetValue(tlskey);
  107. if dataindex=nil then
  108. begin
  109. dataindex:=pointer(LocalAlloc(LMEM_FIXED or LMEM_ZEROINIT,threadvarblocksize));
  110. if dataindex=nil then
  111. RunError(226);
  112. TlsSetValue(tlskey,dataindex);
  113. end;
  114. SetLastError(errorsave);
  115. end;
  116. function SysRelocateThreadvar(offset : dword) : pointer; forward;
  117. procedure SysInitMultithreading;
  118. begin
  119. { do not check IsMultiThread, as program could have altered it, out of Delphi habit }
  120. { the thread attach/detach code uses locks to avoid multiple calls of this }
  121. if TLSKey=$ffffffff then
  122. begin
  123. { We're still running in single thread mode, setup the TLS }
  124. TLSKey:=TlsAlloc;
  125. InitThreadVars(@SysRelocateThreadvar);
  126. IsMultiThread:=true;
  127. end;
  128. end;
  129. procedure SysFiniMultithreading;
  130. begin
  131. if TLSKey<>$ffffffff then
  132. TlsFree(TLSKey);
  133. TLSKey:=$ffffffff;
  134. end;
  135. function SysRelocateThreadvar(offset : dword) : pointer;
  136. var
  137. dataindex : pointer;
  138. errorsave : dword;
  139. begin
  140. errorsave:=GetLastError;
  141. dataindex:=TlsGetValue(tlskey);
  142. if dataindex=nil then
  143. begin
  144. SysAllocateThreadVars;
  145. dataindex:=TlsGetValue(tlskey);
  146. InitThread($1000000);
  147. end;
  148. SetLastError(errorsave);
  149. SysRelocateThreadvar:=DataIndex+Offset;
  150. end;
  151. procedure SysReleaseThreadVars;
  152. var
  153. p: pointer;
  154. begin
  155. if TLSKey<>$ffffffff then
  156. begin
  157. p:=TlsGetValue(tlskey);
  158. if Assigned(p) then
  159. LocalFree(p);
  160. TlsSetValue(tlskey, nil);
  161. end;
  162. end;
  163. {*****************************************************************************
  164. Thread starting
  165. *****************************************************************************}
  166. type
  167. pthreadinfo = ^tthreadinfo;
  168. tthreadinfo = record
  169. f : tthreadfunc;
  170. p : pointer;
  171. stklen : ptruint;
  172. end;
  173. function ThreadMain(param : pointer) : Longint; {$ifdef wince}cdecl{$else}stdcall{$endif};
  174. var
  175. ti : tthreadinfo;
  176. begin
  177. { Copy parameter to local data }
  178. ti:=pthreadinfo(param)^;
  179. { Handle all possible threadvar models:
  180. - dynamic threadvars: initialized either in DllMain,
  181. or upon accessing the threadvar ThreadID;
  182. - static threadvars+TLS callback: initialized in TLS callback;
  183. - static threadvars, no callback: ThreadID remains 0 and
  184. initialization happens here. }
  185. if ThreadID=TThreadID(0) then
  186. InitThread(ti.stklen);
  187. dispose(pthreadinfo(param));
  188. { Start thread function }
  189. {$ifdef DEBUG_MT}
  190. writeln('Jumping to thread function of thread ',Win32GetCurrentThreadId);
  191. {$endif DEBUG_MT}
  192. {$if defined(FPC_USE_WIN64_SEH) or defined(FPC_USE_WIN32_SEH)}
  193. { use special 'top-level' exception handler around the thread function }
  194. ThreadMain:=main_wrapper(ti.p,pointer(ti.f));
  195. {$else FPC_USE_WIN64_SEH}
  196. ThreadMain:=ti.f(ti.p);
  197. {$endif FPC_USE_WIN64_SEH or FPC_USE_WIN32_SEH}
  198. end;
  199. function SysBeginThread(sa : Pointer;stacksize : ptruint;
  200. ThreadFunction : tthreadfunc;p : pointer;
  201. creationFlags : dword;var ThreadId : TThreadID) : TThreadID;
  202. var
  203. ti : pthreadinfo;
  204. _threadid : dword;
  205. begin
  206. {$ifdef DEBUG_MT}
  207. writeln('Creating new thread');
  208. {$endif DEBUG_MT}
  209. { Initialize multithreading if not done }
  210. SysInitMultithreading;
  211. { the only way to pass data to the newly created thread
  212. in a MT safe way, is to use the heap }
  213. new(ti);
  214. ti^.f:=ThreadFunction;
  215. ti^.p:=p;
  216. ti^.stklen:=stacksize;
  217. {$ifdef DEBUG_MT}
  218. writeln('Starting new thread');
  219. {$endif DEBUG_MT}
  220. _threadid:=0;
  221. SysBeginThread:=CreateThread(sa,stacksize,@ThreadMain,ti,creationflags,_threadid);
  222. { creation failed? if yes, we dispose the parameter record }
  223. if SysBeginThread=0 then
  224. begin
  225. {$ifdef DEBUG_MT}
  226. writeln('Thread creation failed');
  227. {$endif DEBUG_MT}
  228. dispose(ti);
  229. end;
  230. ThreadID:=_threadid;
  231. end;
  232. procedure SysEndThread(ExitCode : DWord);
  233. begin
  234. DoneThread;
  235. ExitThread(ExitCode);
  236. end;
  237. procedure SysThreadSwitch;
  238. begin
  239. Sleep(0);
  240. end;
  241. function SysSuspendThread (threadHandle : TThreadID) : dword;
  242. begin
  243. SysSuspendThread:=WinSuspendThread(threadHandle);
  244. end;
  245. function SysResumeThread (threadHandle : TThreadID) : dword;
  246. begin
  247. SysResumeThread:=WinResumeThread(threadHandle);
  248. end;
  249. function SysKillThread (threadHandle : TThreadID) : dword;
  250. var exitCode : dword;
  251. begin
  252. if not TerminateThread (threadHandle, exitCode) then
  253. SysKillThread := GetLastError
  254. else
  255. SysKillThread := 0;
  256. end;
  257. function SysCloseThread (threadHandle : TThreadID) : dword;
  258. begin
  259. SysCloseThread:=winCloseHandle(threadHandle);
  260. end;
  261. function SysWaitForThreadTerminate (threadHandle : TThreadID; TimeoutMs : longint) : dword;
  262. begin
  263. if timeoutMs = 0 then dec (timeoutMs); // $ffffffff is INFINITE
  264. SysWaitForThreadTerminate := WaitForSingleObject(threadHandle, TimeoutMs);
  265. end;
  266. function SysThreadSetPriority (threadHandle : TThreadID; Prio: longint): boolean; {-15..+15, 0=normal}
  267. begin
  268. SysThreadSetPriority:=WinThreadSetPriority(threadHandle,Prio);
  269. end;
  270. function SysThreadGetPriority (threadHandle : TThreadID): longint;
  271. begin
  272. SysThreadGetPriority:=WinThreadGetPriority(threadHandle);
  273. end;
  274. function SysGetCurrentThreadId : TThreadID;
  275. begin
  276. SysGetCurrentThreadId:=Win32GetCurrentThreadId;
  277. end;
  278. {*****************************************************************************
  279. Delphi/Win32 compatibility
  280. *****************************************************************************}
  281. procedure SySInitCriticalSection(var cs);
  282. begin
  283. WinInitCriticalSection(PRTLCriticalSection(@cs)^);
  284. end;
  285. procedure SysDoneCriticalSection(var cs);
  286. begin
  287. WinDoneCriticalSection(PRTLCriticalSection(@cs)^);
  288. end;
  289. procedure SysEnterCriticalSection(var cs);
  290. begin
  291. WinEnterCriticalSection(PRTLCriticalSection(@cs)^);
  292. end;
  293. {$ifdef SUPPORT_WIN95}
  294. function Win95TryEnterCriticalSection(var cs : TRTLCriticalSection):longint;stdcall;
  295. var
  296. MyThreadID : DWORD;
  297. begin
  298. MyThreadId:=GetCurrentThreadId();
  299. if InterlockedIncrement(cs.LockCount)=0 then
  300. begin
  301. cs.OwningThread:=MyThreadId;
  302. cs.RecursionCount:=1;
  303. result:=1;
  304. end
  305. else
  306. begin
  307. if cs.OwningThread=MyThreadId then
  308. begin
  309. InterlockedDecrement(cs.LockCount);
  310. InterlockedIncrement(cs.RecursionCount);
  311. result:=1;
  312. end
  313. else
  314. begin
  315. InterlockedDecrement(cs.LockCount);
  316. result:=0;
  317. end;
  318. end;
  319. end;
  320. {$endif SUPPORT_WIN95}
  321. function SysTryEnterCriticalSection(var cs):longint;
  322. begin
  323. result:=WinTryEnterCriticalSection(PRTLCriticalSection(@cs)^);
  324. end;
  325. procedure SySLeaveCriticalSection(var cs);
  326. begin
  327. WinLeaveCriticalSection(PRTLCriticalSection(@cs)^);
  328. end;
  329. Const
  330. wrSignaled = 0;
  331. wrTimeout = 1;
  332. wrAbandoned= 2;
  333. wrError = 3;
  334. type Tbasiceventstate=record
  335. fhandle : THandle;
  336. flasterror : longint;
  337. end;
  338. plocaleventrec= ^tbasiceventstate;
  339. function intBasicEventCreate(EventAttributes : Pointer;
  340. AManualReset,InitialState : Boolean;const Name : ansistring):pEventState;
  341. begin
  342. new(plocaleventrec(result));
  343. plocaleventrec(result)^.FHandle := CreateEvent(EventAttributes, AManualReset, InitialState,PChar(Name));
  344. end;
  345. procedure intbasiceventdestroy(state:peventstate);
  346. begin
  347. closehandle(plocaleventrec(state)^.fhandle);
  348. dispose(plocaleventrec(state));
  349. end;
  350. procedure intbasiceventResetEvent(state:peventstate);
  351. begin
  352. ResetEvent(plocaleventrec(state)^.FHandle)
  353. end;
  354. procedure intbasiceventSetEvent(state:peventstate);
  355. begin
  356. SetEvent(plocaleventrec(state)^.FHandle);
  357. end;
  358. function intbasiceventWaitFor(Timeout : Cardinal;state:peventstate) : longint;
  359. begin
  360. case WaitForSingleObject(plocaleventrec(state)^.fHandle, Timeout) of
  361. WAIT_ABANDONED: Result := wrAbandoned;
  362. WAIT_OBJECT_0: Result := wrSignaled;
  363. WAIT_TIMEOUT: Result := wrTimeout;
  364. WAIT_FAILED:
  365. begin
  366. Result := wrError;
  367. plocaleventrec(state)^.FLastError := GetLastError;
  368. end;
  369. else
  370. Result := wrError;
  371. end;
  372. end;
  373. function intRTLEventCreate: PRTLEvent;
  374. begin
  375. Result := PRTLEVENT(CreateEvent(nil, false, false, nil));
  376. end;
  377. procedure intRTLEventDestroy(AEvent: PRTLEvent);
  378. begin
  379. CloseHandle(THANDLE(AEvent));
  380. end;
  381. procedure intRTLEventSetEvent(AEvent: PRTLEvent);
  382. begin
  383. SetEvent(THANDLE(AEvent));
  384. end;
  385. procedure intRTLEventResetEvent(AEvent: PRTLEvent);
  386. begin
  387. ResetEvent(THANDLE(AEvent));
  388. end;
  389. procedure intRTLEventWaitFor(AEvent: PRTLEvent);
  390. const
  391. INFINITE=dword(-1);
  392. begin
  393. WaitForSingleObject(THANDLE(AEvent), INFINITE);
  394. end;
  395. procedure intRTLEventWaitForTimeout(AEvent: PRTLEvent;timeout : longint);
  396. begin
  397. WaitForSingleObject(THANDLE(AEvent), timeout);
  398. end;
  399. Var
  400. WinThreadManager : TThreadManager;
  401. Procedure InitSystemThreads;public name '_FPC_InitSystemThreads';
  402. {$IFDEF SUPPORT_WIN95}
  403. var
  404. KernelHandle : THandle;
  405. {$ENDIF SUPPORT_WIN95}
  406. begin
  407. With WinThreadManager do
  408. begin
  409. InitManager :=Nil;
  410. DoneManager :=Nil;
  411. BeginThread :=@SysBeginThread;
  412. EndThread :=@SysEndThread;
  413. SuspendThread :=@SysSuspendThread;
  414. ResumeThread :=@SysResumeThread;
  415. KillThread :=@SysKillThread;
  416. ThreadSwitch :=@SysThreadSwitch;
  417. CloseThread :=@SysCloseThread;
  418. WaitForThreadTerminate :=@SysWaitForThreadTerminate;
  419. ThreadSetPriority :=@SysThreadSetPriority;
  420. ThreadGetPriority :=@SysThreadGetPriority;
  421. GetCurrentThreadId :=@SysGetCurrentThreadId;
  422. InitCriticalSection :=@SysInitCriticalSection;
  423. DoneCriticalSection :=@SysDoneCriticalSection;
  424. EnterCriticalSection :=@SysEnterCriticalSection;
  425. TryEnterCriticalSection:=@SysTryEnterCriticalSection;
  426. LeaveCriticalSection :=@SysLeaveCriticalSection;
  427. InitThreadVar :=@SysInitThreadVar;
  428. RelocateThreadVar :=@SysRelocateThreadVar;
  429. AllocateThreadVars :=@SysAllocateThreadVars;
  430. ReleaseThreadVars :=@SysReleaseThreadVars;
  431. BasicEventCreate :=@intBasicEventCreate;
  432. BasicEventDestroy :=@intBasicEventDestroy;
  433. BasicEventResetEvent :=@intBasicEventResetEvent;
  434. BasicEventSetEvent :=@intBasicEventSetEvent;
  435. BasiceventWaitFor :=@intBasiceventWaitFor;
  436. RTLEventCreate :=@intRTLEventCreate;
  437. RTLEventDestroy :=@intRTLEventDestroy;
  438. RTLEventSetEvent :=@intRTLEventSetEvent;
  439. RTLEventResetEvent :=@intRTLEventResetEvent;
  440. RTLEventWaitFor :=@intRTLEventWaitFor;
  441. RTLEventWaitForTimeout :=@intRTLEventWaitForTimeout;
  442. end;
  443. SetThreadManager(WinThreadManager);
  444. ThreadID := GetCurrentThreadID;
  445. {$ifndef FPC_USE_TLS_DIRECTORY}
  446. if IsLibrary then
  447. {$endif}
  448. SysInitMultithreading;
  449. {$IFDEF SUPPORT_WIN95}
  450. { Try to find TryEnterCriticalSection function }
  451. KernelHandle:=GetModuleHandle(KernelDLL);
  452. if KernelHandle<>0 then
  453. WinTryEnterCriticalSection:=TTryEnterCriticalSection(GetProcAddress(KernelHandle,'TryEnterCriticalSection'));
  454. if not assigned(WinTryEnterCriticalSection) then
  455. WinTryEnterCriticalSection:=@Win95TryEnterCriticalSection;
  456. {$ENDIF SUPPORT_WIN95}
  457. end;