tthread.inc 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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. { ok, so this is a hack, but it works nicely. Just never use
  45. a multiline argument with WRITE_DEBUG! }
  46. {$MACRO ON}
  47. {$IFDEF DEBUG_MT}
  48. {$define WRITE_DEBUG := writeln} // actually write something
  49. {$ELSE}
  50. {$define WRITE_DEBUG := //} // just comment out those lines
  51. {$ENDIF}
  52. // ========== semaphore stuff ==========
  53. {
  54. I don't like this. It eats up 2 filedescriptors for each thread,
  55. and those are a limited resource. If you have a server programm
  56. handling client connections (one per thread) it will not be able
  57. to handle many if we use 2 fds already for internal structures.
  58. However, right now I don't see a better option unless some sem_*
  59. functions are added to systhrds.
  60. I encapsulated all used functions here to make it easier to
  61. change them completely.
  62. }
  63. function SemaphoreInit: Pointer;
  64. begin
  65. SemaphoreInit := GetMem(SizeOf(TFilDes));
  66. fppipe(PFilDes(SemaphoreInit)^);
  67. WRITE_DEBUG('Opened file descriptor ',PFilDes(SemaphoreInit)^[0]);
  68. end;
  69. procedure SemaphoreWait(const FSem: Pointer);
  70. var
  71. b: byte;
  72. begin
  73. WRITE_DEBUG('Waiting for file descriptor ',PFilDes(FSem)^[0]);
  74. repeat
  75. if fpread(PFilDes(FSem)^[0], b, 1) = -1 then
  76. WRITE_DEBUG('Error reading from semaphore ',PFilDes(FSem)^[0],' error = ',fpgeterrno);
  77. until fpgeterrno <> ESysEIntr;
  78. end;
  79. procedure SemaphorePost(const FSem: Pointer);
  80. {$ifdef VER2_0}
  81. var
  82. b : byte;
  83. {$endif}
  84. begin
  85. WRITE_DEBUG('Activating file descriptor ',PFilDes(FSem)^[0]);
  86. {$ifdef VER2_0}
  87. b:=0;
  88. fpwrite(PFilDes(FSem)^[1], b, 1);
  89. {$else}
  90. if fpwrite(PFilDes(FSem)^[1], #0, 1) = -1 then
  91. WRITE_DEBUG('Error writing file descriptor ',PFilDes(FSem)^[0],' error = ',fpgeterrno);
  92. {$endif}
  93. end;
  94. procedure SemaphoreDestroy(const FSem: Pointer);
  95. begin
  96. WRITE_DEBUG('Closing file descriptor ',PFilDes(FSem)^[0]);
  97. fpclose(PFilDes(FSem)^[0]);
  98. fpclose(PFilDes(FSem)^[1]);
  99. FreeMemory(FSem);
  100. end;
  101. // =========== semaphore end ===========
  102. var
  103. ThreadsInited: boolean = false;
  104. const
  105. // stupid, considering its not even implemented...
  106. Priorities: array [TThreadPriority] of Integer =
  107. (-20,-19,-10,0,9,18,19);
  108. procedure InitThreads;
  109. begin
  110. if not ThreadsInited then begin
  111. ThreadsInited := true;
  112. end;
  113. end;
  114. procedure DoneThreads;
  115. begin
  116. ThreadsInited := false;
  117. end;
  118. function ThreadFunc(parameter: Pointer): LongInt;
  119. var
  120. LThread: TThread;
  121. begin
  122. WRITE_DEBUG('ThreadFunc is here...');
  123. LThread := TThread(parameter);
  124. WRITE_DEBUG('thread initing, parameter = ', LongInt(LThread));
  125. try
  126. if LThread.FInitialSuspended then begin
  127. SemaphoreWait(LThread.FSem);
  128. if not LThread.FSuspended then begin
  129. LThread.FInitialSuspended := false;
  130. WRITE_DEBUG('going into LThread.Execute');
  131. LThread.Execute;
  132. end;
  133. end else begin
  134. WRITE_DEBUG('going into LThread.Execute');
  135. LThread.Execute;
  136. end;
  137. except
  138. on e: exception do begin
  139. WRITE_DEBUG('got exception: ',e.message);
  140. LThread.FFatalException := TObject(AcquireExceptionObject);
  141. // not sure if we should really do this...
  142. // but .Destroy was called, so why not try FreeOnTerminate?
  143. if e is EThreadDestroyCalled then LThread.FFreeOnTerminate := true;
  144. end;
  145. end;
  146. WRITE_DEBUG('thread done running');
  147. Result := LThread.FReturnValue;
  148. WRITE_DEBUG('Result is ',Result);
  149. LThread.FFinished := True;
  150. LThread.DoTerminate;
  151. if LThread.FreeOnTerminate then begin
  152. WRITE_DEBUG('Thread should be freed');
  153. LThread.Free;
  154. WRITE_DEBUG('Thread freed');
  155. end;
  156. WRITE_DEBUG('thread func calling EndThread');
  157. EndThread(Result);
  158. end;
  159. { TThread }
  160. constructor TThread.Create(CreateSuspended: Boolean;
  161. const StackSize: SizeUInt = DefaultStackSize);
  162. begin
  163. // lets just hope that the user doesn't create a thread
  164. // via BeginThread and creates the first TThread Object in there!
  165. InitThreads;
  166. inherited Create;
  167. FSem := SemaphoreInit;
  168. FSuspended := CreateSuspended;
  169. FSuspendedExternal := false;
  170. FInitialSuspended := CreateSuspended;
  171. FFatalException := nil;
  172. WRITE_DEBUG('creating thread, self = ',longint(self));
  173. FHandle:= BeginThread(@ThreadFunc, Pointer(Self), FThreadID, StackSize);
  174. WRITE_DEBUG('TThread.Create done');
  175. end;
  176. destructor TThread.Destroy;
  177. begin
  178. if (FThreadID = GetCurrentThreadID) and not(FFreeOnTerminate) and not ffinished then begin
  179. raise EThreadDestroyCalled.Create('A thread cannot destroy itself except by setting FreeOnTerminate and leaving!');
  180. end;
  181. // if someone calls .Free on a thread with
  182. // FreeOnTerminate, then don't crash!
  183. FFreeOnTerminate := false;
  184. if not FFinished and not FSuspended then begin
  185. Terminate;
  186. WaitFor;
  187. end;
  188. if (FInitialSuspended) then begin
  189. // thread was created suspended but never woken up.
  190. SemaphorePost(FSem);
  191. WaitFor;
  192. end;
  193. FFatalException.Free;
  194. FFatalException := nil;
  195. SemaphoreDestroy(FSem);
  196. inherited Destroy;
  197. end;
  198. procedure TThread.SetSuspended(Value: Boolean);
  199. begin
  200. if Value <> FSuspended then
  201. if Value then
  202. Suspend
  203. else
  204. Resume;
  205. end;
  206. procedure TThread.Suspend;
  207. begin
  208. if not FSuspended then begin
  209. if FThreadID = GetCurrentThreadID then begin
  210. FSuspended := true;
  211. SemaphoreWait(FSem);
  212. end else begin
  213. FSuspendedExternal := true;
  214. SuspendThread(FHandle);
  215. end;
  216. end;
  217. end;
  218. procedure TThread.Resume;
  219. begin
  220. if (not FSuspendedExternal) then begin
  221. if FSuspended then begin
  222. FSuspended := False;
  223. SemaphorePost(FSem);
  224. end;
  225. end else begin
  226. FSuspendedExternal := false;
  227. ResumeThread(FHandle);
  228. end;
  229. end;
  230. procedure TThread.Terminate;
  231. begin
  232. FTerminated := True;
  233. end;
  234. function TThread.WaitFor: Integer;
  235. begin
  236. WRITE_DEBUG('waiting for thread ',ptrint(FHandle));
  237. WaitFor := WaitForThreadTerminate(FHandle, 0);
  238. WRITE_DEBUG('thread terminated');
  239. end;
  240. procedure TThread.CallOnTerminate;
  241. begin
  242. // no need to check if FOnTerminate <> nil, because
  243. // thats already done in DoTerminate
  244. FOnTerminate(self);
  245. end;
  246. procedure TThread.DoTerminate;
  247. begin
  248. if Assigned(FOnTerminate) then
  249. Synchronize(@CallOnTerminate);
  250. end;
  251. function TThread.GetPriority: TThreadPriority;
  252. var
  253. P: Integer;
  254. I: TThreadPriority;
  255. begin
  256. P := ThreadGetPriority(FHandle);
  257. Result := tpNormal;
  258. for I := Low(TThreadPriority) to High(TThreadPriority) do
  259. if Priorities[I] = P then
  260. Result := I;
  261. end;
  262. procedure TThread.SetPriority(Value: TThreadPriority);
  263. begin
  264. ThreadSetPriority(FHandle, Priorities[Value]);
  265. end;