tthread.inc 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. {
  2. This file is part of the Free Component Library (FCL)
  3. Copyright (c) 1999-2000 by Peter Vreman
  4. Linux 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. // ========== semaphore stuff ==========
  45. {
  46. I don't like this. It eats up 2 filedescriptors for each thread,
  47. and those are a limited resource. If you have a server programm
  48. handling client connections (one per thread) it will not be able
  49. to handle many if we use 2 fds already for internal structures.
  50. However, right now I don't see a better option unless some sem_*
  51. functions are added to systhrds.
  52. I encapsulated all used functions here to make it easier to
  53. change them completely.
  54. }
  55. function SemaphoreInit: Pointer;
  56. begin
  57. SemaphoreInit := GetMem(SizeOf(TFilDes));
  58. fppipe(PFilDes(SemaphoreInit)^);
  59. end;
  60. procedure SemaphoreWait(const FSem: Pointer);
  61. var
  62. b: byte;
  63. begin
  64. fpread(PFilDes(FSem)^[0], b, 1);
  65. end;
  66. procedure SemaphorePost(const FSem: Pointer);
  67. begin
  68. fpwrite(PFilDes(FSem)^[1], #0, 1);
  69. end;
  70. procedure SemaphoreDestroy(const FSem: Pointer);
  71. begin
  72. fpclose(PFilDes(FSem)^[0]);
  73. fpclose(PFilDes(FSem)^[1]);
  74. FreeMemory(FSem);
  75. end;
  76. // =========== semaphore end ===========
  77. var
  78. ThreadsInited: boolean = false;
  79. {$IFDEF LINUX}
  80. GMainPID: LongInt = 0;
  81. {$ENDIF}
  82. const
  83. // stupid, considering its not even implemented...
  84. Priorities: array [TThreadPriority] of Integer =
  85. (-20,-19,-10,0,9,18,19);
  86. procedure InitThreads;
  87. begin
  88. if not ThreadsInited then begin
  89. ThreadsInited := true;
  90. {$IFDEF LINUX}
  91. GMainPid := fpgetpid();
  92. {$ENDIF}
  93. end;
  94. end;
  95. procedure DoneThreads;
  96. begin
  97. ThreadsInited := false;
  98. end;
  99. { ok, so this is a hack, but it works nicely. Just never use
  100. a multiline argument with WRITE_DEBUG! }
  101. {$MACRO ON}
  102. {$IFDEF DEBUG_MT}
  103. {$define WRITE_DEBUG := writeln} // actually write something
  104. {$ELSE}
  105. {$define WRITE_DEBUG := //} // just comment out those lines
  106. {$ENDIF}
  107. function ThreadFunc(parameter: Pointer): PtrInt;
  108. var
  109. LThread: TThread;
  110. c: char;
  111. begin
  112. WRITE_DEBUG('ThreadFunc is here...');
  113. LThread := TThread(parameter);
  114. {$IFDEF LINUX}
  115. // save the PID of the "thread"
  116. // this is different from the PID of the main thread if
  117. // the LinuxThreads implementation is used
  118. LThread.FPid := fpgetpid();
  119. {$ENDIF}
  120. WRITE_DEBUG('thread initing, parameter = ', LongInt(LThread));
  121. try
  122. if LThread.FInitialSuspended then begin
  123. SemaphoreWait(LThread.FSem);
  124. if not LThread.FSuspended then begin
  125. LThread.FInitialSuspended := false;
  126. WRITE_DEBUG('going into LThread.Execute');
  127. LThread.Execute;
  128. end;
  129. end else begin
  130. WRITE_DEBUG('going into LThread.Execute');
  131. LThread.Execute;
  132. end;
  133. except
  134. on e: exception do begin
  135. WRITE_DEBUG('got exception: ',e.message);
  136. LThread.FFatalException := TObject(AcquireExceptionObject);
  137. // not sure if we should really do this...
  138. // but .Destroy was called, so why not try FreeOnTerminate?
  139. if e is EThreadDestroyCalled then
  140. 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
  174. raise EThreadDestroyCalled.Create('A thread cannot destroy itself except by setting FreeOnTerminate and leaving!');
  175. // if someone calls .Free on a thread with
  176. // FreeOnTerminate, then don't crash!
  177. FFreeOnTerminate := false;
  178. if not FFinished and not FSuspended then begin
  179. Terminate;
  180. WaitFor;
  181. end;
  182. if (FInitialSuspended) then begin
  183. // thread was created suspended but never woken up.
  184. SemaphorePost(FSem);
  185. WaitFor;
  186. end;
  187. FFatalException.Free;
  188. FFatalException := nil;
  189. SemaphoreDestroy(FSem);
  190. inherited Destroy;
  191. end;
  192. procedure TThread.SetSuspended(Value: Boolean);
  193. begin
  194. if Value <> FSuspended then
  195. if Value then
  196. Suspend
  197. else
  198. Resume;
  199. end;
  200. procedure TThread.Suspend;
  201. begin
  202. if not FSuspended then begin
  203. if FThreadID = GetCurrentThreadID then begin
  204. FSuspended := true;
  205. SemaphoreWait(FSem);
  206. end else begin
  207. FSuspendedExternal := true;
  208. {$IFDEF LINUX}
  209. // naughty hack if the user doesn't have Linux with NPTL...
  210. // in that case, the PID of threads will not be identical
  211. // to the other threads, which means that our thread is a normal
  212. // process that we can suspend via SIGSTOP...
  213. // this violates POSIX, but is the way it works on the
  214. // LinuxThreads pthread implementation. Not with NPTL, but in that case
  215. // getpid(2) also behaves properly and returns the same PID for
  216. // all threads. Thats actually (FINALLY!) native thread support :-)
  217. if FPid <> GMainPID then begin
  218. FSuspended := true;
  219. fpkill(FPid, SIGSTOP);
  220. end;
  221. {$ELSE}
  222. SuspendThread(FHandle);
  223. {$ENDIF}
  224. end;
  225. end;
  226. end;
  227. procedure TThread.Resume;
  228. begin
  229. if (not FSuspendedExternal) then begin
  230. if FSuspended then begin
  231. FSuspended := False;
  232. SemaphorePost(FSem);
  233. end;
  234. end else begin
  235. FSuspendedExternal := false;
  236. {$IFDEF LINUX}
  237. // see .Suspend
  238. if FPid <> GMainPID then begin
  239. FSuspended := False;
  240. fpkill(FPid, SIGCONT);
  241. end;
  242. {$ELSE}
  243. ResumeThread(FHandle);
  244. {$ENDIF}
  245. end;
  246. end;
  247. procedure TThread.Terminate;
  248. begin
  249. FTerminated := True;
  250. end;
  251. function TThread.WaitFor: Integer;
  252. begin
  253. WRITE_DEBUG('waiting for thread ',FHandle);
  254. WaitFor := WaitForThreadTerminate(FHandle, 0);
  255. WRITE_DEBUG('thread terminated');
  256. end;
  257. procedure TThread.CallOnTerminate;
  258. begin
  259. // no need to check if FOnTerminate <> nil, because
  260. // thats already done in DoTerminate
  261. FOnTerminate(self);
  262. end;
  263. procedure TThread.DoTerminate;
  264. begin
  265. if Assigned(FOnTerminate) then
  266. Synchronize(@CallOnTerminate);
  267. end;
  268. function TThread.GetPriority: TThreadPriority;
  269. var
  270. P: Integer;
  271. I: TThreadPriority;
  272. begin
  273. P := ThreadGetPriority(FHandle);
  274. Result := tpNormal;
  275. for I := Low(TThreadPriority) to High(TThreadPriority) do
  276. if Priorities[I] = P then
  277. Result := I;
  278. end;
  279. procedure TThread.SetPriority(Value: TThreadPriority);
  280. begin
  281. ThreadSetPriority(FHandle, Priorities[Value]);
  282. end;