systhrd.inc 18 KB

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