tthread.inc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. {
  2. $Id$
  3. This file is part of the Free Component Library (FCL)
  4. Copyright (c) 1999-2000 by Peter Vreman
  5. Linux TThread 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. What follows, is a short description on my implementation of TThread.
  14. Most information can also be found by reading the source and accompanying
  15. comments.
  16. A thread is created using BeginThread, which in turn calls
  17. pthread_create. So the threads here are always posix threads.
  18. Posix doesn't define anything for suspending threads as this is
  19. inherintly unsafe. Just don't suspend threads at points they cannot
  20. control. Therefore, I didn't implement .Suspend() if its called from
  21. outside the threads execution flow (except on Linux _without_ NPTL).
  22. The implementation for .suspend uses a semaphore, which is initialized
  23. at thread creation. If the thread tries to suspend itself, we simply
  24. let it wait on the semaphore until it is unblocked by someone else
  25. who calls .Resume.
  26. If a thread is supposed to be suspended (from outside its own path of
  27. execution) on a system where the symbol LINUX is defined, two things
  28. are possible.
  29. 1) the system has the LinuxThreads pthread implementation
  30. 2) the system has NPTL as the pthread implementation.
  31. In the first case, each thread is a process on its own, which as far as
  32. know actually violates posix with respect to signal handling.
  33. But we can detect this case, because getpid(2) will
  34. return a different PID for each thread. In that case, sending SIGSTOP
  35. to the PID associated with a thread will actually stop that thread
  36. only.
  37. In the second case, this is not possible. But getpid(2) returns the same
  38. PID across all threads, which is detected, and TThread.Suspend() does
  39. nothing in that case. This should probably be changed, but I know of
  40. no way to suspend a thread when using NPTL.
  41. If the symbol LINUX is not defined, then the unimplemented
  42. function SuspendThread is called.
  43. Johannes Berg <[email protected]>, Sunday, November 16 2003
  44. }
  45. // ========== semaphore stuff ==========
  46. {
  47. I don't like this. It eats up 2 filedescriptors for each thread,
  48. and those are a limited resource. If you have a server programm
  49. handling client connections (one per thread) it will not be able
  50. to handle many if we use 2 fds already for internal structures.
  51. However, right now I don't see a better option unless some sem_*
  52. functions are added to systhrds.
  53. I encapsulated all used functions here to make it easier to
  54. change them completely.
  55. }
  56. var
  57. { event that happens when gui thread is done executing the method
  58. }
  59. ExecuteEvent: PRtlEvent;
  60. { guard for synchronization variables }
  61. SynchronizeCritSect: TRtlCriticalSection;
  62. { method to execute }
  63. SynchronizeMethod: TThreadMethod;
  64. { caught exception in gui thread, to be raised in calling thread }
  65. SynchronizeException: Exception;
  66. function SemaphoreInit: Pointer;
  67. begin
  68. SemaphoreInit := GetMem(SizeOf(TFilDes));
  69. fppipe(PFilDes(SemaphoreInit)^);
  70. end;
  71. procedure SemaphoreWait(const FSem: Pointer);
  72. var
  73. b: byte;
  74. begin
  75. fpread(PFilDes(FSem)^[0], b, 1);
  76. end;
  77. procedure SemaphorePost(const FSem: Pointer);
  78. begin
  79. fpwrite(PFilDes(FSem)^[1], #0, 1);
  80. end;
  81. procedure SemaphoreDestroy(const FSem: Pointer);
  82. begin
  83. fpclose(PFilDes(FSem)^[0]);
  84. fpclose(PFilDes(FSem)^[1]);
  85. FreeMemory(FSem);
  86. end;
  87. // =========== semaphore end ===========
  88. var
  89. ThreadsInited: boolean = false;
  90. {$IFDEF LINUX}
  91. GMainPID: LongInt = 0;
  92. {$ENDIF}
  93. const
  94. // stupid, considering its not even implemented...
  95. Priorities: array [TThreadPriority] of Integer =
  96. (-20,-19,-10,0,9,18,19);
  97. procedure InitThreads;
  98. begin
  99. if not ThreadsInited then begin
  100. ThreadsInited := true;
  101. {$IFDEF LINUX}
  102. GMainPid := fpgetpid();
  103. {$ENDIF}
  104. end;
  105. end;
  106. procedure DoneThreads;
  107. begin
  108. ThreadsInited := false;
  109. end;
  110. { ok, so this is a hack, but it works nicely. Just never use
  111. a multiline argument with WRITE_DEBUG! }
  112. {$MACRO ON}
  113. {$IFDEF DEBUG_MT}
  114. {$define WRITE_DEBUG := writeln} // actually write something
  115. {$ELSE}
  116. {$define WRITE_DEBUG := //} // just comment out those lines
  117. {$ENDIF}
  118. function ThreadFunc(parameter: Pointer): PtrInt;
  119. var
  120. LThread: TThread;
  121. c: char;
  122. begin
  123. WRITE_DEBUG('ThreadFunc is here...');
  124. LThread := TThread(parameter);
  125. {$IFDEF LINUX}
  126. // save the PID of the "thread"
  127. // this is different from the PID of the main thread if
  128. // the LinuxThreads implementation is used
  129. LThread.FPid := fpgetpid();
  130. {$ENDIF}
  131. WRITE_DEBUG('thread initing, parameter = ', LongInt(LThread));
  132. try
  133. if LThread.FInitialSuspended then begin
  134. SemaphoreWait(LThread.FSem);
  135. if not LThread.FInitialSuspended then begin
  136. WRITE_DEBUG('going into LThread.Execute');
  137. LThread.Execute;
  138. end;
  139. end else begin
  140. WRITE_DEBUG('going into LThread.Execute');
  141. LThread.Execute;
  142. end;
  143. except
  144. on e: exception do begin
  145. WRITE_DEBUG('got exception: ',e.message);
  146. LThread.FFatalException := TObject(AcquireExceptionObject);
  147. // not sure if we should really do this...
  148. // but .Destroy was called, so why not try FreeOnTerminate?
  149. if e is EThreadDestroyCalled then LThread.FFreeOnTerminate := true;
  150. end;
  151. end;
  152. WRITE_DEBUG('thread done running');
  153. Result := LThread.FReturnValue;
  154. WRITE_DEBUG('Result is ',Result);
  155. LThread.FFinished := True;
  156. LThread.DoTerminate;
  157. if LThread.FreeOnTerminate then begin
  158. WRITE_DEBUG('Thread should be freed');
  159. LThread.Free;
  160. WRITE_DEBUG('Thread freed');
  161. end;
  162. WRITE_DEBUG('thread func exiting');
  163. end;
  164. { TThread }
  165. constructor TThread.Create(CreateSuspended: Boolean);
  166. begin
  167. // lets just hope that the user doesn't create a thread
  168. // via BeginThread and creates the first TThread Object in there!
  169. InitThreads;
  170. inherited Create;
  171. FSem := SemaphoreInit;
  172. FSuspended :=CreateSuspended;
  173. FSuspendedExternal := false;
  174. FInitialSuspended := CreateSuspended;
  175. FFatalException := nil;
  176. WRITE_DEBUG('creating thread, self = ',longint(self));
  177. FHandle:= BeginThread(@ThreadFunc, Pointer(Self), FThreadID);
  178. WRITE_DEBUG('TThread.Create done');
  179. end;
  180. destructor TThread.Destroy;
  181. begin
  182. if FThreadID = GetCurrentThreadID then begin
  183. raise EThreadDestroyCalled.Create('A thread cannot destroy itself except by setting FreeOnTerminate and leaving!');
  184. end;
  185. // if someone calls .Free on a thread with
  186. // FreeOnTerminate, then don't crash!
  187. FFreeOnTerminate := false;
  188. if not FFinished and not FSuspended then begin
  189. Terminate;
  190. WaitFor;
  191. end;
  192. if (FInitialSuspended) then begin
  193. // thread was created suspended but never woken up.
  194. SemaphorePost(FSem);
  195. WaitFor;
  196. end;
  197. FFatalException.Free;
  198. FFatalException := nil;
  199. SemaphoreDestroy(FSem);
  200. inherited Destroy;
  201. end;
  202. procedure TThread.SetSuspended(Value: Boolean);
  203. begin
  204. if Value <> FSuspended then
  205. if Value then
  206. Suspend
  207. else
  208. Resume;
  209. end;
  210. procedure TThread.Suspend;
  211. begin
  212. if not FSuspended then begin
  213. if FThreadID = GetCurrentThreadID then begin
  214. FSuspended := true;
  215. SemaphoreWait(FSem);
  216. end else begin
  217. FSuspendedExternal := true;
  218. {$IFDEF LINUX}
  219. // naughty hack if the user doesn't have Linux with NPTL...
  220. // in that case, the PID of threads will not be identical
  221. // to the other threads, which means that our thread is a normal
  222. // process that we can suspend via SIGSTOP...
  223. // this violates POSIX, but is the way it works on the
  224. // LinuxThreads pthread implementation. Not with NPTL, but in that case
  225. // getpid(2) also behaves properly and returns the same PID for
  226. // all threads. Thats actually (FINALLY!) native thread support :-)
  227. if FPid <> GMainPID then begin
  228. FSuspended := true;
  229. fpkill(FPid, SIGSTOP);
  230. end;
  231. {$ELSE}
  232. SuspendThread(FHandle);
  233. {$ENDIF}
  234. end;
  235. end;
  236. end;
  237. procedure TThread.Resume;
  238. begin
  239. if (not FSuspendedExternal) then begin
  240. if FSuspended then begin
  241. SemaphorePost(FSem);
  242. FInitialSuspended := false;
  243. FSuspended := False;
  244. end;
  245. end else begin
  246. {$IFDEF LINUX}
  247. // see .Suspend
  248. if FPid <> GMainPID then begin
  249. fpkill(FPid, SIGCONT);
  250. FSuspended := False;
  251. end;
  252. {$ELSE}
  253. ResumeThread(FHandle);
  254. {$ENDIF}
  255. FSuspendedExternal := false;
  256. end;
  257. end;
  258. procedure TThread.Terminate;
  259. begin
  260. FTerminated := True;
  261. end;
  262. function TThread.WaitFor: Integer;
  263. begin
  264. WRITE_DEBUG('waiting for thread ',FHandle);
  265. WaitFor := WaitForThreadTerminate(FHandle, 0);
  266. WRITE_DEBUG('thread terminated');
  267. end;
  268. procedure TThread.CallOnTerminate;
  269. begin
  270. // no need to check if FOnTerminate <> nil, because
  271. // thats already done in DoTerminate
  272. FOnTerminate(self);
  273. end;
  274. procedure TThread.DoTerminate;
  275. begin
  276. if Assigned(FOnTerminate) then
  277. Synchronize(@CallOnTerminate);
  278. end;
  279. function TThread.GetPriority: TThreadPriority;
  280. var
  281. P: Integer;
  282. I: TThreadPriority;
  283. begin
  284. P := ThreadGetPriority(FHandle);
  285. Result := tpNormal;
  286. for I := Low(TThreadPriority) to High(TThreadPriority) do
  287. if Priorities[I] = P then
  288. Result := I;
  289. end;
  290. procedure TThread.Synchronize(Method: TThreadMethod);
  291. var
  292. LocalSyncException: Exception;
  293. begin
  294. if SynchronizeMethodProc = nil then
  295. { raise some error? }
  296. exit;
  297. EnterCriticalSection(SynchronizeCritSect);
  298. SynchronizeMethod := Method;
  299. SynchronizeException := nil;
  300. SynchronizeMethodProc;
  301. // wait infinitely
  302. RtlEventWaitFor(ExecuteEvent);
  303. SynchronizeMethod := nil;
  304. LocalSyncException := SynchronizeException;
  305. LeaveCriticalSection(SynchronizeCritSect);
  306. if LocalSyncException <> nil then
  307. raise LocalSyncException;
  308. end;
  309. procedure CheckSynchronize;
  310. { assumes being called from GUI thread }
  311. begin
  312. if SynchronizeMethod = nil then
  313. exit;
  314. try
  315. SynchronizeMethod;
  316. except
  317. SynchronizeException := Exception(AcquireExceptionObject);
  318. end;
  319. RtlEventSetEvent(ExecuteEvent);
  320. end;
  321. procedure TThread.SetPriority(Value: TThreadPriority);
  322. begin
  323. ThreadSetPriority(FHandle, Priorities[Value]);
  324. end;
  325. {
  326. $Log$
  327. Revision 1.9 2004-12-23 09:42:42 marco
  328. * first tthread.synchronize support (merged neli's patches)
  329. Revision 1.8 2004/12/12 14:30:27 peter
  330. * x86_64 updates
  331. Revision 1.7 2004/03/03 22:00:37 peter
  332. * remove cdecl
  333. Revision 1.6 2003/11/22 11:04:08 marco
  334. * Johill: suspend fix
  335. Revision 1.5 2003/11/19 15:51:54 peter
  336. * tthread disabled for 1.0.x
  337. Revision 1.4 2003/11/17 08:27:49 marco
  338. * pthreads based ttread from Johannes Berg
  339. Revision 1.3 2003/11/10 16:54:28 marco
  340. * new oldlinux unit. 1_0 defines killed in some former FCL parts.
  341. Revision 1.2 2003/11/03 09:42:28 marco
  342. * Peter's Cardinal<->Longint fixes patch
  343. Revision 1.1 2003/10/06 21:01:06 peter
  344. * moved classes unit to rtl
  345. Revision 1.9 2003/10/06 17:06:55 florian
  346. * applied Johannes Berg's patch for exception handling in threads
  347. Revision 1.8 2003/09/20 15:10:30 marco
  348. * small fixes. fcl now compiles
  349. Revision 1.7 2002/12/18 20:44:36 peter
  350. * use fillchar to clear sigset
  351. Revision 1.6 2002/09/07 15:15:27 peter
  352. * old logs removed and tabs fixed
  353. }