tthread.inc 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. {
  2. $Id$
  3. This file is part of the Free Component Library (FCL)
  4. Copyright (c) 1999-2000 by Peter Vreman
  5. Darwin 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. function SemaphoreInit: Pointer;
  57. begin
  58. SemaphoreInit := GetMem(SizeOf(TFilDes));
  59. fppipe(PFilDes(SemaphoreInit)^);
  60. end;
  61. procedure SemaphoreWait(const FSem: Pointer);
  62. var
  63. b: byte;
  64. begin
  65. fpread(PFilDes(FSem)^[0], b, 1);
  66. end;
  67. procedure SemaphorePost(const FSem: Pointer);
  68. begin
  69. fpwrite(PFilDes(FSem)^[1], #0, 1);
  70. end;
  71. procedure SemaphoreDestroy(const FSem: Pointer);
  72. begin
  73. fpclose(PFilDes(FSem)^[0]);
  74. fpclose(PFilDes(FSem)^[1]);
  75. FreeMemory(FSem);
  76. end;
  77. // =========== semaphore end ===========
  78. var
  79. ThreadsInited: boolean = false;
  80. const
  81. // stupid, considering its not even implemented...
  82. Priorities: array [TThreadPriority] of Integer =
  83. (-20,-19,-10,0,9,18,19);
  84. procedure InitThreads;
  85. begin
  86. if not ThreadsInited then begin
  87. ThreadsInited := true;
  88. end;
  89. end;
  90. procedure DoneThreads;
  91. begin
  92. ThreadsInited := false;
  93. end;
  94. { ok, so this is a hack, but it works nicely. Just never use
  95. a multiline argument with WRITE_DEBUG! }
  96. {$MACRO ON}
  97. {$IFDEF DEBUG_MT}
  98. {$define WRITE_DEBUG := writeln} // actually write something
  99. {$ELSE}
  100. {$define WRITE_DEBUG := //} // just comment out those lines
  101. {$ENDIF}
  102. function ThreadFunc(parameter: Pointer): LongInt;
  103. var
  104. LThread: TThread;
  105. c: char;
  106. begin
  107. WRITE_DEBUG('ThreadFunc is here...');
  108. LThread := TThread(parameter);
  109. WRITE_DEBUG('thread initing, parameter = ', LongInt(LThread));
  110. try
  111. if LThread.FInitialSuspended then begin
  112. SemaphoreWait(LThread.FSem);
  113. if not LThread.FInitialSuspended then begin
  114. WRITE_DEBUG('going into LThread.Execute');
  115. LThread.Execute;
  116. end;
  117. end else begin
  118. WRITE_DEBUG('going into LThread.Execute');
  119. LThread.Execute;
  120. end;
  121. except
  122. on e: exception do begin
  123. WRITE_DEBUG('got exception: ',e.message);
  124. LThread.FFatalException := TObject(AcquireExceptionObject);
  125. // not sure if we should really do this...
  126. // but .Destroy was called, so why not try FreeOnTerminate?
  127. if e is EThreadDestroyCalled then LThread.FFreeOnTerminate := true;
  128. end;
  129. end;
  130. WRITE_DEBUG('thread done running');
  131. Result := LThread.FReturnValue;
  132. WRITE_DEBUG('Result is ',Result);
  133. LThread.FFinished := True;
  134. LThread.DoTerminate;
  135. if LThread.FreeOnTerminate then begin
  136. WRITE_DEBUG('Thread should be freed');
  137. LThread.Free;
  138. WRITE_DEBUG('Thread freed');
  139. end;
  140. WRITE_DEBUG('thread func exiting');
  141. end;
  142. { TThread }
  143. constructor TThread.Create(CreateSuspended: Boolean);
  144. begin
  145. // lets just hope that the user doesn't create a thread
  146. // via BeginThread and creates the first TThread Object in there!
  147. InitThreads;
  148. inherited Create;
  149. FSem := SemaphoreInit;
  150. FSuspended := CreateSuspended;
  151. FSuspendedExternal := false;
  152. FInitialSuspended := CreateSuspended;
  153. FFatalException := nil;
  154. WRITE_DEBUG('creating thread, self = ',longint(self));
  155. FHandle:= BeginThread(@ThreadFunc, Pointer(Self), FThreadID);
  156. WRITE_DEBUG('TThread.Create done');
  157. end;
  158. destructor TThread.Destroy;
  159. begin
  160. if FThreadID = GetCurrentThreadID then begin
  161. raise EThreadDestroyCalled.Create('A thread cannot destroy itself except by setting FreeOnTerminate and leaving!');
  162. end;
  163. // if someone calls .Free on a thread with
  164. // FreeOnTerminate, then don't crash!
  165. FFreeOnTerminate := false;
  166. if not FFinished and not FSuspended then begin
  167. Terminate;
  168. WaitFor;
  169. end;
  170. if (FInitialSuspended) then begin
  171. // thread was created suspended but never woken up.
  172. SemaphorePost(FSem);
  173. WaitFor;
  174. end;
  175. FFatalException.Free;
  176. FFatalException := nil;
  177. SemaphoreDestroy(FSem);
  178. inherited Destroy;
  179. end;
  180. procedure TThread.SetSuspended(Value: Boolean);
  181. begin
  182. if Value <> FSuspended then
  183. if Value then
  184. Suspend
  185. else
  186. Resume;
  187. end;
  188. procedure TThread.Suspend;
  189. begin
  190. if not FSuspended then begin
  191. if FThreadID = GetCurrentThreadID then begin
  192. FSuspended := true;
  193. SemaphoreWait(FSem);
  194. end else begin
  195. FSuspendedExternal := true;
  196. SuspendThread(FHandle);
  197. end;
  198. end;
  199. end;
  200. procedure TThread.Resume;
  201. begin
  202. if (not FSuspendedExternal) then begin
  203. if FSuspended then begin
  204. SemaphorePost(FSem);
  205. FInitialSuspended := false;
  206. FSuspended := False;
  207. end;
  208. end else begin
  209. ResumeThread(FHandle);
  210. FSuspendedExternal := false;
  211. end;
  212. end;
  213. procedure TThread.Terminate;
  214. begin
  215. FTerminated := True;
  216. end;
  217. function TThread.WaitFor: Integer;
  218. begin
  219. WRITE_DEBUG('waiting for thread ',FHandle);
  220. WaitFor := WaitForThreadTerminate(FHandle, 0);
  221. WRITE_DEBUG('thread terminated');
  222. end;
  223. procedure TThread.CallOnTerminate;
  224. begin
  225. // no need to check if FOnTerminate <> nil, because
  226. // thats already done in DoTerminate
  227. FOnTerminate(self);
  228. end;
  229. procedure TThread.DoTerminate;
  230. begin
  231. if Assigned(FOnTerminate) then
  232. Synchronize(@CallOnTerminate);
  233. end;
  234. function TThread.GetPriority: TThreadPriority;
  235. var
  236. P: Integer;
  237. I: TThreadPriority;
  238. begin
  239. P := ThreadGetPriority(FHandle);
  240. Result := tpNormal;
  241. for I := Low(TThreadPriority) to High(TThreadPriority) do
  242. if Priorities[I] = P then
  243. Result := I;
  244. end;
  245. procedure TThread.Synchronize(Method: TThreadMethod);
  246. begin
  247. {$TODO someone with more clue of the GUI stuff will have to do this}
  248. end;
  249. procedure TThread.SetPriority(Value: TThreadPriority);
  250. begin
  251. ThreadSetPriority(FHandle, Priorities[Value]);
  252. end;
  253. {
  254. $Log$
  255. Revision 1.3 2004-03-04 12:42:44 jonas
  256. - removed legacy code
  257. Revision 1.2 2004/03/04 12:34:36 jonas
  258. * fixed compilation
  259. Revision 1.1 2004/01/04 20:05:38 jonas
  260. * first working version of the Darwin/Mac OS X (for PowerPC) RTL
  261. Several non-essential units are still missing, but make cycle works
  262. Revision 1.7 2003/11/22 11:04:08 marco
  263. * Johill: suspend fix
  264. Revision 1.6 2003/11/19 10:12:02 marco
  265. * more cleanups
  266. Revision 1.5 2003/11/17 10:05:51 marco
  267. * threads for FreeBSD. Not working tho
  268. Revision 1.4 2003/11/17 08:27:49 marco
  269. * pthreads based ttread from Johannes Berg
  270. Revision 1.3 2003/11/10 16:54:28 marco
  271. * new oldlinux unit. 1_0 defines killed in some former FCL parts.
  272. Revision 1.2 2003/11/03 09:42:28 marco
  273. * Peter's Cardinal<->Longint fixes patch
  274. Revision 1.1 2003/10/06 21:01:06 peter
  275. * moved classes unit to rtl
  276. Revision 1.9 2003/10/06 17:06:55 florian
  277. * applied Johannes Berg's patch for exception handling in threads
  278. Revision 1.8 2003/09/20 15:10:30 marco
  279. * small fixes. fcl now compiles
  280. Revision 1.7 2002/12/18 20:44:36 peter
  281. * use fillchar to clear sigset
  282. Revision 1.6 2002/09/07 15:15:27 peter
  283. * old logs removed and tabs fixed
  284. }