tthread.inc 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. {
  2. This file is part of the Free Component Library (FCL)
  3. Copyright (c) 1999-2000 by Peter Vreman
  4. Darwin TThread implementation
  5. See the file COPYING.FPC, included in this distribution,
  6. for details about the copyright.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  10. **********************************************************************}
  11. {
  12. What follows, is a short description on my implementation of TThread.
  13. Most information can also be found by reading the source and accompanying
  14. comments.
  15. A thread is created using BeginThread, which in turn calls
  16. pthread_create. So the threads here are always posix threads.
  17. Posix doesn't define anything for suspending threads as this is
  18. inherintly unsafe. Just don't suspend threads at points they cannot
  19. control. Therefore, I didn't implement .Suspend() if its called from
  20. outside the threads execution flow (except on Linux _without_ NPTL).
  21. The implementation for .suspend uses a semaphore, which is initialized
  22. at thread creation. If the thread tries to suspend itself, we simply
  23. let it wait on the semaphore until it is unblocked by someone else
  24. who calls .Resume.
  25. If a thread is supposed to be suspended (from outside its own path of
  26. execution) on a system where the symbol LINUX is defined, two things
  27. are possible.
  28. 1) the system has the LinuxThreads pthread implementation
  29. 2) the system has NPTL as the pthread implementation.
  30. In the first case, each thread is a process on its own, which as far as
  31. know actually violates posix with respect to signal handling.
  32. But we can detect this case, because getpid(2) will
  33. return a different PID for each thread. In that case, sending SIGSTOP
  34. to the PID associated with a thread will actually stop that thread
  35. only.
  36. In the second case, this is not possible. But getpid(2) returns the same
  37. PID across all threads, which is detected, and TThread.Suspend() does
  38. nothing in that case. This should probably be changed, but I know of
  39. no way to suspend a thread when using NPTL.
  40. If the symbol LINUX is not defined, then the unimplemented
  41. function SuspendThread is called.
  42. Johannes Berg <[email protected]>, Sunday, November 16 2003
  43. }
  44. // ========== semaphore stuff ==========
  45. {
  46. I don't like this. It eats up 2 filedescriptors for each thread,
  47. and those are a limited resource. If you have a server programm
  48. handling client connections (one per thread) it will not be able
  49. to handle many if we use 2 fds already for internal structures.
  50. However, right now I don't see a better option unless some sem_*
  51. functions are added to systhrds.
  52. I encapsulated all used functions here to make it easier to
  53. change them completely.
  54. }
  55. function SemaphoreInit: Pointer;
  56. begin
  57. SemaphoreInit := GetMem(SizeOf(TFilDes));
  58. fppipe(PFilDes(SemaphoreInit)^);
  59. end;
  60. procedure SemaphoreWait(const FSem: Pointer);
  61. var
  62. b: byte;
  63. begin
  64. fpread(PFilDes(FSem)^[0], b, 1);
  65. end;
  66. procedure SemaphorePost(const FSem: Pointer);
  67. begin
  68. fpwrite(PFilDes(FSem)^[1], #0, 1);
  69. end;
  70. procedure SemaphoreDestroy(const FSem: Pointer);
  71. begin
  72. fpclose(PFilDes(FSem)^[0]);
  73. fpclose(PFilDes(FSem)^[1]);
  74. FreeMemory(FSem);
  75. end;
  76. // =========== semaphore end ===========
  77. var
  78. ThreadsInited: boolean = false;
  79. const
  80. // stupid, considering its not even implemented...
  81. Priorities: array [TThreadPriority] of Integer =
  82. (-20,-19,-10,0,9,18,19);
  83. procedure InitThreads;
  84. begin
  85. if not ThreadsInited then begin
  86. ThreadsInited := true;
  87. end;
  88. end;
  89. procedure DoneThreads;
  90. begin
  91. ThreadsInited := false;
  92. end;
  93. { ok, so this is a hack, but it works nicely. Just never use
  94. a multiline argument with WRITE_DEBUG! }
  95. {$MACRO ON}
  96. {$IFDEF DEBUG_MT}
  97. {$define WRITE_DEBUG := writeln} // actually write something
  98. {$ELSE}
  99. {$define WRITE_DEBUG := //} // just comment out those lines
  100. {$ENDIF}
  101. function ThreadFunc(parameter: Pointer): LongInt;
  102. var
  103. LThread: TThread;
  104. begin
  105. WRITE_DEBUG('ThreadFunc is here...');
  106. LThread := TThread(parameter);
  107. WRITE_DEBUG('thread initing, parameter = ', LongInt(LThread));
  108. try
  109. if LThread.FInitialSuspended then begin
  110. SemaphoreWait(LThread.FSem);
  111. if not LThread.FSuspended then begin
  112. LThread.FInitialSuspended := false;
  113. WRITE_DEBUG('going into LThread.Execute');
  114. LThread.Execute;
  115. end;
  116. end else begin
  117. WRITE_DEBUG('going into LThread.Execute');
  118. LThread.Execute;
  119. end;
  120. except
  121. on e: exception do begin
  122. WRITE_DEBUG('got exception: ',e.message);
  123. LThread.FFatalException := TObject(AcquireExceptionObject);
  124. // not sure if we should really do this...
  125. // but .Destroy was called, so why not try FreeOnTerminate?
  126. if e is EThreadDestroyCalled then LThread.FFreeOnTerminate := true;
  127. end;
  128. end;
  129. WRITE_DEBUG('thread done running');
  130. Result := LThread.FReturnValue;
  131. WRITE_DEBUG('Result is ',Result);
  132. LThread.FFinished := True;
  133. LThread.DoTerminate;
  134. if LThread.FreeOnTerminate then begin
  135. WRITE_DEBUG('Thread should be freed');
  136. LThread.Free;
  137. WRITE_DEBUG('Thread freed');
  138. end;
  139. WRITE_DEBUG('thread func exiting');
  140. end;
  141. { TThread }
  142. constructor TThread.Create(CreateSuspended: Boolean);
  143. begin
  144. // lets just hope that the user doesn't create a thread
  145. // via BeginThread and creates the first TThread Object in there!
  146. InitThreads;
  147. inherited Create;
  148. FSem := SemaphoreInit;
  149. FSuspended := CreateSuspended;
  150. FSuspendedExternal := false;
  151. FInitialSuspended := CreateSuspended;
  152. FFatalException := nil;
  153. WRITE_DEBUG('creating thread, self = ',longint(self));
  154. FHandle:= BeginThread(@ThreadFunc, Pointer(Self), FThreadID);
  155. WRITE_DEBUG('TThread.Create done');
  156. end;
  157. destructor TThread.Destroy;
  158. begin
  159. if FThreadID = GetCurrentThreadID then begin
  160. raise EThreadDestroyCalled.Create('A thread cannot destroy itself except by setting FreeOnTerminate and leaving!');
  161. end;
  162. // if someone calls .Free on a thread with
  163. // FreeOnTerminate, then don't crash!
  164. FFreeOnTerminate := false;
  165. if not FFinished and not FSuspended then begin
  166. Terminate;
  167. WaitFor;
  168. end;
  169. if (FInitialSuspended) then begin
  170. // thread was created suspended but never woken up.
  171. SemaphorePost(FSem);
  172. WaitFor;
  173. end;
  174. FFatalException.Free;
  175. FFatalException := nil;
  176. SemaphoreDestroy(FSem);
  177. inherited Destroy;
  178. end;
  179. procedure TThread.SetSuspended(Value: Boolean);
  180. begin
  181. if Value <> FSuspended then
  182. if Value then
  183. Suspend
  184. else
  185. Resume;
  186. end;
  187. procedure TThread.Suspend;
  188. begin
  189. if not FSuspended then begin
  190. if FThreadID = GetCurrentThreadID then begin
  191. FSuspended := true;
  192. SemaphoreWait(FSem);
  193. end else begin
  194. FSuspendedExternal := true;
  195. SuspendThread(FHandle);
  196. end;
  197. end;
  198. end;
  199. procedure TThread.Resume;
  200. begin
  201. if (not FSuspendedExternal) then begin
  202. if FSuspended then begin
  203. FSuspended := False;
  204. SemaphorePost(FSem);
  205. end;
  206. end else begin
  207. FSuspendedExternal := false;
  208. ResumeThread(FHandle);
  209. end;
  210. end;
  211. procedure TThread.Terminate;
  212. begin
  213. FTerminated := True;
  214. end;
  215. function TThread.WaitFor: Integer;
  216. begin
  217. WRITE_DEBUG('waiting for thread ',FHandle);
  218. WaitFor := WaitForThreadTerminate(FHandle, 0);
  219. WRITE_DEBUG('thread terminated');
  220. end;
  221. procedure TThread.CallOnTerminate;
  222. begin
  223. // no need to check if FOnTerminate <> nil, because
  224. // thats already done in DoTerminate
  225. FOnTerminate(self);
  226. end;
  227. procedure TThread.DoTerminate;
  228. begin
  229. if Assigned(FOnTerminate) then
  230. Synchronize(@CallOnTerminate);
  231. end;
  232. function TThread.GetPriority: TThreadPriority;
  233. var
  234. P: Integer;
  235. I: TThreadPriority;
  236. begin
  237. P := ThreadGetPriority(FHandle);
  238. Result := tpNormal;
  239. for I := Low(TThreadPriority) to High(TThreadPriority) do
  240. if Priorities[I] = P then
  241. Result := I;
  242. end;
  243. procedure TThread.SetPriority(Value: TThreadPriority);
  244. begin
  245. ThreadSetPriority(FHandle, Priorities[Value]);
  246. end;