systhrd.inc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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;
  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;
  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 : cardinal;
  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. 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. {$ifdef SUPPORT_WIN95}
  289. function Win95TryEnterCriticalSection(var cs : TRTLCriticalSection):longint;stdcall;
  290. var
  291. MyThreadID : DWORD;
  292. begin
  293. MyThreadId:=GetCurrentThreadId();
  294. if InterlockedIncrement(cs.LockCount)=0 then
  295. begin
  296. cs.OwningThread:=MyThreadId;
  297. cs.RecursionCount:=1;
  298. result:=1;
  299. end
  300. else
  301. begin
  302. if cs.OwningThread=MyThreadId then
  303. begin
  304. InterlockedDecrement(cs.LockCount);
  305. InterlockedIncrement(cs.RecursionCount);
  306. result:=1;
  307. end
  308. else
  309. begin
  310. InterlockedDecrement(cs.LockCount);
  311. result:=0;
  312. end;
  313. end;
  314. end;
  315. {$endif SUPPORT_WIN95}
  316. function SysTryEnterCriticalSection(var cs):longint;
  317. begin
  318. result:=WinTryEnterCriticalSection(PRTLCriticalSection(@cs)^);
  319. end;
  320. procedure SySLeaveCriticalSection(var cs);
  321. begin
  322. WinLeaveCriticalSection(PRTLCriticalSection(@cs)^);
  323. end;
  324. Const
  325. wrSignaled = 0;
  326. wrTimeout = 1;
  327. wrAbandoned= 2;
  328. wrError = 3;
  329. type Tbasiceventstate=record
  330. fhandle : THandle;
  331. flasterror : longint;
  332. end;
  333. plocaleventrec= ^tbasiceventstate;
  334. function intBasicEventCreate(EventAttributes : Pointer;
  335. AManualReset,InitialState : Boolean;const Name : ansistring):pEventState;
  336. begin
  337. new(plocaleventrec(result));
  338. plocaleventrec(result)^.FHandle := CreateEvent(EventAttributes, AManualReset, InitialState,PChar(Name));
  339. end;
  340. procedure intbasiceventdestroy(state:peventstate);
  341. begin
  342. closehandle(plocaleventrec(state)^.fhandle);
  343. dispose(plocaleventrec(state));
  344. end;
  345. procedure intbasiceventResetEvent(state:peventstate);
  346. begin
  347. ResetEvent(plocaleventrec(state)^.FHandle)
  348. end;
  349. procedure intbasiceventSetEvent(state:peventstate);
  350. begin
  351. SetEvent(plocaleventrec(state)^.FHandle);
  352. end;
  353. function intbasiceventWaitFor(Timeout : Cardinal;state:peventstate) : longint;
  354. begin
  355. case WaitForSingleObject(plocaleventrec(state)^.fHandle, Timeout) of
  356. WAIT_ABANDONED: Result := wrAbandoned;
  357. WAIT_OBJECT_0: Result := wrSignaled;
  358. WAIT_TIMEOUT: Result := wrTimeout;
  359. WAIT_FAILED:
  360. begin
  361. Result := wrError;
  362. plocaleventrec(state)^.FLastError := GetLastError;
  363. end;
  364. else
  365. Result := wrError;
  366. end;
  367. end;
  368. function intRTLEventCreate: PRTLEvent;
  369. begin
  370. Result := PRTLEVENT(CreateEvent(nil, false, false, nil));
  371. end;
  372. procedure intRTLEventDestroy(AEvent: PRTLEvent);
  373. begin
  374. CloseHandle(THANDLE(AEvent));
  375. end;
  376. procedure intRTLEventSetEvent(AEvent: PRTLEvent);
  377. begin
  378. SetEvent(THANDLE(AEvent));
  379. end;
  380. procedure intRTLEventResetEvent(AEvent: PRTLEvent);
  381. begin
  382. ResetEvent(THANDLE(AEvent));
  383. end;
  384. procedure intRTLEventWaitFor(AEvent: PRTLEvent);
  385. const
  386. INFINITE=dword(-1);
  387. begin
  388. WaitForSingleObject(THANDLE(AEvent), INFINITE);
  389. end;
  390. procedure intRTLEventWaitForTimeout(AEvent: PRTLEvent;timeout : longint);
  391. begin
  392. WaitForSingleObject(THANDLE(AEvent), timeout);
  393. end;
  394. Var
  395. WinThreadManager : TThreadManager;
  396. Procedure InitSystemThreads;
  397. {$IFDEF SUPPORT_WIN95}
  398. var
  399. KernelHandle : THandle;
  400. {$ENDIF SUPPORT_WIN95}
  401. begin
  402. With WinThreadManager do
  403. begin
  404. InitManager :=Nil;
  405. DoneManager :=Nil;
  406. BeginThread :=@SysBeginThread;
  407. EndThread :=@SysEndThread;
  408. SuspendThread :=@SysSuspendThread;
  409. ResumeThread :=@SysResumeThread;
  410. KillThread :=@SysKillThread;
  411. ThreadSwitch :=@SysThreadSwitch;
  412. CloseThread :=@SysCloseThread;
  413. WaitForThreadTerminate :=@SysWaitForThreadTerminate;
  414. ThreadSetPriority :=@SysThreadSetPriority;
  415. ThreadGetPriority :=@SysThreadGetPriority;
  416. GetCurrentThreadId :=@SysGetCurrentThreadId;
  417. InitCriticalSection :=@SysInitCriticalSection;
  418. DoneCriticalSection :=@SysDoneCriticalSection;
  419. EnterCriticalSection :=@SysEnterCriticalSection;
  420. TryEnterCriticalSection:=@SysTryEnterCriticalSection;
  421. LeaveCriticalSection :=@SysLeaveCriticalSection;
  422. InitThreadVar :=@SysInitThreadVar;
  423. RelocateThreadVar :=@SysRelocateThreadVar;
  424. AllocateThreadVars :=@SysAllocateThreadVars;
  425. ReleaseThreadVars :=@SysReleaseThreadVars;
  426. BasicEventCreate :=@intBasicEventCreate;
  427. BasicEventDestroy :=@intBasicEventDestroy;
  428. BasicEventResetEvent :=@intBasicEventResetEvent;
  429. BasicEventSetEvent :=@intBasicEventSetEvent;
  430. BasiceventWaitFor :=@intBasiceventWaitFor;
  431. RTLEventCreate :=@intRTLEventCreate;
  432. RTLEventDestroy :=@intRTLEventDestroy;
  433. RTLEventSetEvent :=@intRTLEventSetEvent;
  434. RTLEventResetEvent :=@intRTLEventResetEvent;
  435. RTLEventWaitFor :=@intRTLEventWaitFor;
  436. RTLEventWaitForTimeout :=@intRTLEventWaitForTimeout;
  437. end;
  438. SetThreadManager(WinThreadManager);
  439. ThreadID := GetCurrentThreadID;
  440. {$ifndef FPC_USE_TLS_DIRECTORY}
  441. if IsLibrary then
  442. {$endif}
  443. SysInitMultithreading;
  444. {$IFDEF SUPPORT_WIN95}
  445. { Try to find TryEnterCriticalSection function }
  446. KernelHandle:=GetModuleHandle(KernelDLL);
  447. if KernelHandle<>0 then
  448. WinTryEnterCriticalSection:=TTryEnterCriticalSection(GetProcAddress(KernelHandle,'TryEnterCriticalSection'));
  449. if not assigned(WinTryEnterCriticalSection) then
  450. WinTryEnterCriticalSection:=@Win95TryEnterCriticalSection;
  451. {$ENDIF SUPPORT_WIN95}
  452. end;