2
0

systhrd.inc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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:pwidechar): THandle; stdcall; external KernelDLL name 'CreateEventW';
  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. errorsave : dword;
  89. begin
  90. {$ifdef dummy}
  91. { I've no clue why this doesn't read dataindex, imo it should (FK) }
  92. asm
  93. movl TLSKey,%edx
  94. movl $0x2c,%eax
  95. movl %fs:(%eax),%eax
  96. movl (%eax,%edx,4),%eax
  97. movl %eax,dataindex
  98. end;
  99. if DataIndex=nil then
  100. begin
  101. errorsave:=GetLastError;
  102. SysAllocateThreadVars;
  103. DataIndex:=TlsGetValue(tlskey);
  104. SetLastError(errorsave);
  105. end;
  106. {$else win32}
  107. errorsave:=GetLastError;
  108. dataindex:=TlsGetValue(tlskey);
  109. if dataindex=nil then
  110. begin
  111. SysAllocateThreadVars;
  112. dataindex:=TlsGetValue(tlskey);
  113. end;
  114. SetLastError(errorsave);
  115. {$endif win32}
  116. SysRelocateThreadvar:=DataIndex+Offset;
  117. end;
  118. procedure SysReleaseThreadVars;
  119. begin
  120. LocalFree(TlsGetValue(tlskey));
  121. end;
  122. {*****************************************************************************
  123. Thread starting
  124. *****************************************************************************}
  125. type
  126. pthreadinfo = ^tthreadinfo;
  127. tthreadinfo = record
  128. f : tthreadfunc;
  129. p : pointer;
  130. stklen : cardinal;
  131. end;
  132. function ThreadMain(param : pointer) : Longint; {$ifdef wince}cdecl{$else}stdcall{$endif};
  133. var
  134. ti : tthreadinfo;
  135. begin
  136. { Allocate local thread vars, this must be the first thing,
  137. because the exception management and io depends on threadvars }
  138. SysAllocateThreadVars;
  139. { Copy parameter to local data }
  140. {$ifdef DEBUG_MT}
  141. writeln('New thread started, initialising ...');
  142. {$endif DEBUG_MT}
  143. ti:=pthreadinfo(param)^;
  144. dispose(pthreadinfo(param));
  145. { Initialize thread }
  146. InitThread(ti.stklen);
  147. { Start thread function }
  148. {$ifdef DEBUG_MT}
  149. writeln('Jumping to thread function');
  150. {$endif DEBUG_MT}
  151. ThreadMain:=ti.f(ti.p);
  152. end;
  153. function SysBeginThread(sa : Pointer;stacksize : ptruint;
  154. ThreadFunction : tthreadfunc;p : pointer;
  155. creationFlags : dword;var ThreadId : TThreadID) : TThreadID;
  156. var
  157. ti : pthreadinfo;
  158. _threadid : DWord;
  159. begin
  160. {$ifdef DEBUG_MT}
  161. writeln('Creating new thread');
  162. {$endif DEBUG_MT}
  163. { Initialize multithreading if not done }
  164. if not IsMultiThread then
  165. begin
  166. { We're still running in single thread mode, setup the TLS }
  167. TLSKey:=TlsAlloc;
  168. InitThreadVars(@SysRelocateThreadvar);
  169. IsMultiThread:=true;
  170. end;
  171. { the only way to pass data to the newly created thread
  172. in a MT safe way, is to use the heap }
  173. new(ti);
  174. ti^.f:=ThreadFunction;
  175. ti^.p:=p;
  176. ti^.stklen:=stacksize;
  177. { call pthread_create }
  178. {$ifdef DEBUG_MT}
  179. writeln('Starting new thread');
  180. {$endif DEBUG_MT}
  181. _threadid:=ThreadID;
  182. SysBeginThread:=CreateThread(sa,stacksize,@ThreadMain,ti,creationflags,_threadid);
  183. ThreadID:=_threadid;
  184. end;
  185. procedure SysEndThread(ExitCode : DWord);
  186. begin
  187. DoneThread;
  188. ExitThread(ExitCode);
  189. end;
  190. procedure SysThreadSwitch;
  191. begin
  192. Sleep(0);
  193. end;
  194. function SysSuspendThread (threadHandle : TThreadID) : dword;
  195. begin
  196. SysSuspendThread:=WinSuspendThread(threadHandle);
  197. end;
  198. function SysResumeThread (threadHandle : TThreadID) : dword;
  199. begin
  200. SysResumeThread:=WinResumeThread(threadHandle);
  201. end;
  202. function SysKillThread (threadHandle : TThreadID) : dword;
  203. var exitCode : dword;
  204. begin
  205. if not TerminateThread (threadHandle, exitCode) then
  206. SysKillThread := GetLastError
  207. else
  208. SysKillThread := 0;
  209. end;
  210. function SysWaitForThreadTerminate (threadHandle : TThreadID; TimeoutMs : longint) : dword;
  211. begin
  212. if timeoutMs = 0 then dec (timeoutMs); // $ffffffff is INFINITE
  213. SysWaitForThreadTerminate := WaitForSingleObject(threadHandle, TimeoutMs);
  214. end;
  215. function SysThreadSetPriority (threadHandle : TThreadID; Prio: longint): boolean; {-15..+15, 0=normal}
  216. begin
  217. SysThreadSetPriority:=WinThreadSetPriority(threadHandle,Prio);
  218. end;
  219. function SysThreadGetPriority (threadHandle : TThreadID): longint;
  220. begin
  221. SysThreadGetPriority:=WinThreadGetPriority(threadHandle);
  222. end;
  223. function SysGetCurrentThreadId : TThreadID;
  224. begin
  225. SysGetCurrentThreadId:=Win32GetCurrentThreadId;
  226. end;
  227. {*****************************************************************************
  228. Delphi/Win32 compatibility
  229. *****************************************************************************}
  230. procedure WinInitCriticalSection(var cs : TRTLCriticalSection);
  231. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'InitializeCriticalSection';
  232. procedure WinDoneCriticalSection(var cs : TRTLCriticalSection);
  233. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'DeleteCriticalSection';
  234. procedure WinEnterCriticalSection(var cs : TRTLCriticalSection);
  235. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'EnterCriticalSection';
  236. procedure WinLeaveCriticalSection(var cs : TRTLCriticalSection);
  237. {$ifdef wince}cdecl{$else}stdcall{$endif};external KernelDLL name 'LeaveCriticalSection';
  238. procedure SySInitCriticalSection(var cs);
  239. begin
  240. WinInitCriticalSection(PRTLCriticalSection(@cs)^);
  241. end;
  242. procedure SysDoneCriticalSection(var cs);
  243. begin
  244. WinDoneCriticalSection(PRTLCriticalSection(@cs)^);
  245. end;
  246. procedure SysEnterCriticalSection(var cs);
  247. begin
  248. WinEnterCriticalSection(PRTLCriticalSection(@cs)^);
  249. end;
  250. procedure SySLeaveCriticalSection(var cs);
  251. begin
  252. WinLeaveCriticalSection(PRTLCriticalSection(@cs)^);
  253. end;
  254. Const
  255. wrSignaled = 0;
  256. wrTimeout = 1;
  257. wrAbandoned= 2;
  258. wrError = 3;
  259. type Tbasiceventstate=record
  260. fhandle : THandle;
  261. flasterror : longint;
  262. end;
  263. plocaleventrec= ^tbasiceventstate;
  264. function intBasicEventCreate(EventAttributes : Pointer;
  265. AManualReset,InitialState : Boolean;const Name : RtlString):pEventState;
  266. begin
  267. new(plocaleventrec(result));
  268. plocaleventrec(result)^.FHandle := CreateEvent(EventAttributes, AManualReset, InitialState,_W(Name));
  269. end;
  270. procedure intbasiceventdestroy(state:peventstate);
  271. begin
  272. closehandle(plocaleventrec(state)^.fhandle);
  273. dispose(plocaleventrec(state));
  274. end;
  275. procedure intbasiceventResetEvent(state:peventstate);
  276. begin
  277. ResetEvent(plocaleventrec(state)^.FHandle)
  278. end;
  279. procedure intbasiceventSetEvent(state:peventstate);
  280. begin
  281. SetEvent(plocaleventrec(state)^.FHandle);
  282. end;
  283. function intbasiceventWaitFor(Timeout : Cardinal;state:peventstate) : longint;
  284. begin
  285. case WaitForSingleObject(plocaleventrec(state)^.fHandle, Timeout) of
  286. WAIT_ABANDONED: Result := wrAbandoned;
  287. WAIT_OBJECT_0: Result := wrSignaled;
  288. WAIT_TIMEOUT: Result := wrTimeout;
  289. WAIT_FAILED:
  290. begin
  291. Result := wrError;
  292. plocaleventrec(state)^.FLastError := GetLastError;
  293. end;
  294. else
  295. Result := wrError;
  296. end;
  297. end;
  298. function intRTLEventCreate: PRTLEvent;
  299. begin
  300. Result := PRTLEVENT(CreateEvent(nil, false, false, nil));
  301. end;
  302. procedure intRTLEventDestroy(AEvent: PRTLEvent);
  303. begin
  304. CloseHandle(THANDLE(AEvent));
  305. end;
  306. procedure intRTLEventSetEvent(AEvent: PRTLEvent);
  307. begin
  308. SetEvent(THANDLE(AEvent));
  309. end;
  310. procedure intRTLEventResetEvent(AEvent: PRTLEvent);
  311. begin
  312. ResetEvent(THANDLE(AEvent));
  313. end;
  314. procedure intRTLEventWaitFor(AEvent: PRTLEvent);
  315. const
  316. INFINITE=dword(-1);
  317. begin
  318. WaitForSingleObject(THANDLE(AEvent), INFINITE);
  319. end;
  320. procedure intRTLEventWaitForTimeout(AEvent: PRTLEvent;timeout : longint);
  321. begin
  322. WaitForSingleObject(THANDLE(AEvent), timeout);
  323. end;
  324. Var
  325. WinThreadManager : TThreadManager;
  326. Procedure InitSystemThreads;
  327. begin
  328. With WinThreadManager do
  329. begin
  330. InitManager :=Nil;
  331. DoneManager :=Nil;
  332. BeginThread :=@SysBeginThread;
  333. EndThread :=@SysEndThread;
  334. SuspendThread :=@SysSuspendThread;
  335. ResumeThread :=@SysResumeThread;
  336. KillThread :=@SysKillThread;
  337. ThreadSwitch :=@SysThreadSwitch;
  338. WaitForThreadTerminate :=@SysWaitForThreadTerminate;
  339. ThreadSetPriority :=@SysThreadSetPriority;
  340. ThreadGetPriority :=@SysThreadGetPriority;
  341. GetCurrentThreadId :=@SysGetCurrentThreadId;
  342. InitCriticalSection :=@SysInitCriticalSection;
  343. DoneCriticalSection :=@SysDoneCriticalSection;
  344. EnterCriticalSection :=@SysEnterCriticalSection;
  345. LeaveCriticalSection :=@SysLeaveCriticalSection;
  346. InitThreadVar :=@SysInitThreadVar;
  347. RelocateThreadVar :=@SysRelocateThreadVar;
  348. AllocateThreadVars :=@SysAllocateThreadVars;
  349. ReleaseThreadVars :=@SysReleaseThreadVars;
  350. BasicEventCreate :=@intBasicEventCreate;
  351. BasicEventDestroy :=@intBasicEventDestroy;
  352. BasicEventResetEvent :=@intBasicEventResetEvent;
  353. BasicEventSetEvent :=@intBasicEventSetEvent;
  354. BasiceventWaitFor :=@intBasiceventWaitFor;
  355. RTLEventCreate :=@intRTLEventCreate;
  356. RTLEventDestroy :=@intRTLEventDestroy;
  357. RTLEventSetEvent :=@intRTLEventSetEvent;
  358. RTLEventResetEvent :=@intRTLEventResetEvent;
  359. RTLEventWaitFor :=@intRTLEventWaitFor;
  360. RTLEventWaitForTimeout :=@intRTLEventWaitForTimeout;
  361. end;
  362. SetThreadManager(WinThreadManager);
  363. ThreadID := GetCurrentThreadID;
  364. end;