tthread.inc 8.8 KB

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