systhrd.inc 14 KB

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