tthread.inc 8.1 KB

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