systhrd.inc 17 KB

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