tthread.inc 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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. GMainPID: LongInt = 0;
  57. const
  58. // stupid, considering its not even implemented...
  59. Priorities: array [TThreadPriority] of Integer =
  60. (-20,-19,-10,0,9,18,19);
  61. procedure InitThreads;
  62. begin
  63. if not ThreadsInited then begin
  64. GetThreadManager(CurrentTM);
  65. ThreadsInited := true;
  66. GMainPid := fpgetpid();
  67. end;
  68. end;
  69. procedure DoneThreads;
  70. begin
  71. ThreadsInited := false;
  72. end;
  73. function ThreadFunc(parameter: Pointer): PtrInt;
  74. var
  75. LThread: TThread;
  76. c: char;
  77. begin
  78. WRITE_DEBUG('ThreadFunc is here...');
  79. LThread := TThread(parameter);
  80. WRITE_DEBUG('thread initing, parameter = ', LongInt(LThread));
  81. // save the PID of the "thread"
  82. // this is different from the PID of the main thread if
  83. // the LinuxThreads implementation is used
  84. LThread.FPid := fpgetpid();
  85. try
  86. if LThread.FInitialSuspended then begin
  87. CurrentTM.SemaphoreWait(LThread.FSem);
  88. if not LThread.FSuspended then begin
  89. LThread.FInitialSuspended := false;
  90. WRITE_DEBUG('going into LThread.Execute');
  91. LThread.Execute;
  92. end;
  93. end else begin
  94. WRITE_DEBUG('going into LThread.Execute');
  95. LThread.Execute;
  96. end;
  97. except
  98. on e: exception do begin
  99. WRITE_DEBUG('got exception: ',e.message);
  100. LThread.FFatalException := TObject(AcquireExceptionObject);
  101. // not sure if we should really do this...
  102. // but .Destroy was called, so why not try FreeOnTerminate?
  103. if e is EThreadDestroyCalled then LThread.FFreeOnTerminate := true;
  104. end;
  105. end;
  106. WRITE_DEBUG('thread done running');
  107. Result := LThread.FReturnValue;
  108. WRITE_DEBUG('Result is ',Result);
  109. LThread.FFinished := True;
  110. LThread.DoTerminate;
  111. if LThread.FreeOnTerminate then begin
  112. WRITE_DEBUG('Thread should be freed');
  113. LThread.Free;
  114. WRITE_DEBUG('Thread freed');
  115. end;
  116. WRITE_DEBUG('thread func calling EndThread');
  117. EndThread(Result);
  118. end;
  119. { TThread }
  120. constructor TThread.Create(CreateSuspended: Boolean;
  121. const StackSize: SizeUInt = DefaultStackSize);
  122. begin
  123. // lets just hope that the user doesn't create a thread
  124. // via BeginThread and creates the first TThread Object in there!
  125. InitThreads;
  126. inherited Create;
  127. FSem := CurrentTM.SemaphoreInit();
  128. FSuspended := CreateSuspended;
  129. FSuspendedExternal := false;
  130. FInitialSuspended := CreateSuspended;
  131. FFatalException := nil;
  132. WRITE_DEBUG('creating thread, self = ',PtrInt(self));
  133. FHandle:= BeginThread(@ThreadFunc, Pointer(Self), FThreadID,StackSize);
  134. WRITE_DEBUG('TThread.Create done');
  135. end;
  136. destructor TThread.Destroy;
  137. begin
  138. if (FThreadID = GetCurrentThreadID) and not(FFreeOnTerminate) and not ffinished then begin
  139. raise EThreadDestroyCalled.Create('A thread cannot destroy itself except by setting FreeOnTerminate and leaving!');
  140. end;
  141. // if someone calls .Free on a thread with
  142. // FreeOnTerminate, then don't crash!
  143. FFreeOnTerminate := false;
  144. if not FFinished and not FSuspended then begin
  145. Terminate;
  146. WaitFor;
  147. end;
  148. if (FInitialSuspended) then begin
  149. // thread was created suspended but never woken up.
  150. CurrentTM.SemaphorePost(FSem);
  151. WaitFor;
  152. end;
  153. FFatalException.Free;
  154. FFatalException := nil;
  155. CurrentTM.SemaphoreDestroy(FSem);
  156. inherited Destroy;
  157. end;
  158. procedure TThread.SetSuspended(Value: Boolean);
  159. begin
  160. if Value <> FSuspended then
  161. if Value then
  162. Suspend
  163. else
  164. Resume;
  165. end;
  166. procedure TThread.Suspend;
  167. begin
  168. if not FSuspended then begin
  169. if FThreadID = GetCurrentThreadID then begin
  170. FSuspended := true;
  171. CurrentTM.SemaphoreWait(FSem);
  172. end else begin
  173. FSuspendedExternal := true;
  174. // naughty hack if the user doesn't have Linux with NPTL...
  175. // in that case, the PID of threads will not be identical
  176. // to the other threads, which means that our thread is a normal
  177. // process that we can suspend via SIGSTOP...
  178. // this violates POSIX, but is the way it works on the
  179. // LinuxThreads pthread implementation. Not with NPTL, but in that case
  180. // getpid(2) also behaves properly and returns the same PID for
  181. // all threads. Thats actually (FINALLY!) native thread support :-)
  182. if FPid <> GMainPID then begin
  183. FSuspended := true;
  184. fpkill(FPid, SIGSTOP);
  185. end;
  186. end;
  187. end;
  188. end;
  189. procedure TThread.Resume;
  190. begin
  191. if (not FSuspendedExternal) then begin
  192. if FSuspended then begin
  193. FSuspended := False;
  194. CurrentTM.SemaphorePost(FSem);
  195. end;
  196. end else begin
  197. FSuspendedExternal := false;
  198. // see .Suspend
  199. if FPid <> GMainPID then begin
  200. FSuspended := False;
  201. fpkill(FPid, SIGCONT);
  202. end; end;
  203. end;
  204. procedure TThread.Terminate;
  205. begin
  206. FTerminated := True;
  207. end;
  208. function TThread.WaitFor: Integer;
  209. begin
  210. WRITE_DEBUG('waiting for thread ',FHandle);
  211. WaitFor := WaitForThreadTerminate(FHandle, 0);
  212. WRITE_DEBUG('thread terminated');
  213. end;
  214. procedure TThread.CallOnTerminate;
  215. begin
  216. // no need to check if FOnTerminate <> nil, because
  217. // thats already done in DoTerminate
  218. FOnTerminate(self);
  219. end;
  220. procedure TThread.DoTerminate;
  221. begin
  222. if Assigned(FOnTerminate) then
  223. Synchronize(@CallOnTerminate);
  224. end;
  225. function TThread.GetPriority: TThreadPriority;
  226. var
  227. P: Integer;
  228. I: TThreadPriority;
  229. begin
  230. P := ThreadGetPriority(FHandle);
  231. Result := tpNormal;
  232. for I := Low(TThreadPriority) to High(TThreadPriority) do
  233. if Priorities[I] = P then
  234. Result := I;
  235. end;
  236. procedure TThread.SetPriority(Value: TThreadPriority);
  237. begin
  238. ThreadSetPriority(FHandle, Priorities[Value]);
  239. end;