tthread.inc 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. {
  2. This file is part of the Free Pascal run time library.
  3. (c) 2000-2003 by Marco van de Voort
  4. member of the Free Pascal development team.
  5. See the file COPYING.FPC, included in this distribution,
  6. for details about the copyright.
  7. TThread implementation old (1.0) and new (pthreads) style
  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. { ok, so this is a hack, but it works nicely. Just never use
  46. a multiline argument with WRITE_DEBUG! }
  47. {$MACRO ON}
  48. {$IFDEF DEBUG_MT}
  49. {$define WRITE_DEBUG := writeln} // actually write something
  50. {$ELSE}
  51. {$define WRITE_DEBUG := //} // just comment out those lines
  52. {$ENDIF}
  53. var
  54. ThreadsInited: boolean = false;
  55. CurrentTM: TThreadManager;
  56. const
  57. // stupid, considering its not even implemented...
  58. Priorities: array [TThreadPriority] of Integer =
  59. (-20,-19,-10,0,9,18,19);
  60. procedure InitThreads;
  61. begin
  62. if not ThreadsInited then begin
  63. GetThreadManager(CurrentTM);
  64. ThreadsInited := true;
  65. end;
  66. end;
  67. procedure DoneThreads;
  68. begin
  69. ThreadsInited := false;
  70. end;
  71. function ThreadFunc(parameter: Pointer): LongInt;
  72. var
  73. LThread: TThread;
  74. c: char;
  75. begin
  76. WRITE_DEBUG('ThreadFunc is here...');
  77. LThread := TThread(parameter);
  78. WRITE_DEBUG('thread initing, parameter = ', LongInt(LThread));
  79. try
  80. if LThread.FInitialSuspended then begin
  81. CurrentTM.SemaphoreWait(LThread.FSem);
  82. if not LThread.FSuspended then begin
  83. LThread.FInitialSuspended := false;
  84. WRITE_DEBUG('going into LThread.Execute');
  85. LThread.Execute;
  86. end;
  87. end else begin
  88. WRITE_DEBUG('going into LThread.Execute');
  89. LThread.Execute;
  90. end;
  91. except
  92. on e: exception do begin
  93. WRITE_DEBUG('got exception: ',e.message);
  94. LThread.FFatalException := TObject(AcquireExceptionObject);
  95. // not sure if we should really do this...
  96. // but .Destroy was called, so why not try FreeOnTerminate?
  97. if e is EThreadDestroyCalled then LThread.FFreeOnTerminate := true;
  98. end;
  99. end;
  100. WRITE_DEBUG('thread done running');
  101. Result := LThread.FReturnValue;
  102. WRITE_DEBUG('Result is ',Result);
  103. LThread.FFinished := True;
  104. LThread.DoTerminate;
  105. if LThread.FreeOnTerminate then begin
  106. WRITE_DEBUG('Thread should be freed');
  107. LThread.Free;
  108. WRITE_DEBUG('Thread freed');
  109. end;
  110. WRITE_DEBUG('thread func calling EndThread');
  111. EndThread(Result);
  112. end;
  113. { TThread }
  114. constructor TThread.Create(CreateSuspended: Boolean;
  115. const StackSize: SizeUInt = DefaultStackSize);
  116. begin
  117. // lets just hope that the user doesn't create a thread
  118. // via BeginThread and creates the first TThread Object in there!
  119. InitThreads;
  120. inherited Create;
  121. FSem := CurrentTM.SemaphoreInit();
  122. FSuspended := CreateSuspended;
  123. FSuspendedExternal := false;
  124. FInitialSuspended := CreateSuspended;
  125. FFatalException := nil;
  126. WRITE_DEBUG('creating thread, self = ',PtrInt(self));
  127. FHandle:= BeginThread(@ThreadFunc, Pointer(Self), FThreadID,StackSize);
  128. WRITE_DEBUG('TThread.Create done');
  129. end;
  130. destructor TThread.Destroy;
  131. begin
  132. if (FThreadID = GetCurrentThreadID) and not(FFreeOnTerminate) and not ffinished then begin
  133. raise EThreadDestroyCalled.Create('A thread cannot destroy itself except by setting FreeOnTerminate and leaving!');
  134. end;
  135. // if someone calls .Free on a thread with
  136. // FreeOnTerminate, then don't crash!
  137. FFreeOnTerminate := false;
  138. if not FFinished and not FSuspended then begin
  139. Terminate;
  140. WaitFor;
  141. end;
  142. if (FInitialSuspended) then begin
  143. // thread was created suspended but never woken up.
  144. CurrentTM.SemaphorePost(FSem);
  145. WaitFor;
  146. end;
  147. FFatalException.Free;
  148. FFatalException := nil;
  149. CurrentTM.SemaphoreDestroy(FSem);
  150. inherited Destroy;
  151. end;
  152. procedure TThread.SetSuspended(Value: Boolean);
  153. begin
  154. if Value <> FSuspended then
  155. if Value then
  156. Suspend
  157. else
  158. Resume;
  159. end;
  160. procedure TThread.Suspend;
  161. begin
  162. if not FSuspended then begin
  163. if FThreadID = GetCurrentThreadID then begin
  164. FSuspended := true;
  165. CurrentTM.SemaphoreWait(FSem);
  166. end else begin
  167. FSuspendedExternal := true;
  168. SuspendThread(FHandle);
  169. end;
  170. end;
  171. end;
  172. procedure TThread.Resume;
  173. begin
  174. if (not FSuspendedExternal) then begin
  175. if FSuspended then begin
  176. FSuspended := False;
  177. CurrentTM.SemaphorePost(FSem);
  178. end;
  179. end else begin
  180. FSuspendedExternal := false;
  181. ResumeThread(FHandle);
  182. end;
  183. end;
  184. procedure TThread.Terminate;
  185. begin
  186. FTerminated := True;
  187. end;
  188. function TThread.WaitFor: Integer;
  189. begin
  190. WRITE_DEBUG('waiting for thread ',FHandle);
  191. WaitFor := WaitForThreadTerminate(FHandle, 0);
  192. WRITE_DEBUG('thread terminated');
  193. end;
  194. procedure TThread.CallOnTerminate;
  195. begin
  196. // no need to check if FOnTerminate <> nil, because
  197. // thats already done in DoTerminate
  198. FOnTerminate(self);
  199. end;
  200. procedure TThread.DoTerminate;
  201. begin
  202. if Assigned(FOnTerminate) then
  203. Synchronize(@CallOnTerminate);
  204. end;
  205. function TThread.GetPriority: TThreadPriority;
  206. var
  207. P: Integer;
  208. I: TThreadPriority;
  209. begin
  210. P := ThreadGetPriority(FHandle);
  211. Result := tpNormal;
  212. for I := Low(TThreadPriority) to High(TThreadPriority) do
  213. if Priorities[I] = P then
  214. Result := I;
  215. end;
  216. procedure TThread.SetPriority(Value: TThreadPriority);
  217. begin
  218. ThreadSetPriority(FHandle, Priorities[Value]);
  219. end;