tthread.inc 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. {
  2. $Id: tthread.inc,v 1.5 2005/03/01 20:38:49 jonas Exp $
  3. This file is part of the Free Pascal run time library.
  4. (c) 2000-2003 by Marco van de Voort
  5. member of the Free Pascal development team.
  6. See the file COPYING.FPC, included in this distribution,
  7. for details about the copyright.
  8. TThread implementation old (1.0) and new (pthreads) style
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY;without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  12. }
  13. {
  14. What follows, is a short description on my implementation of TThread.
  15. Most information can also be found by reading the source and accompanying
  16. comments.
  17. A thread is created using BeginThread, which in turn calls
  18. pthread_create. So the threads here are always posix threads.
  19. Posix doesn't define anything for suspending threads as this is
  20. inherintly unsafe. Just don't suspend threads at points they cannot
  21. control. Therefore, I didn't implement .Suspend() if its called from
  22. outside the threads execution flow (except on Linux _without_ NPTL).
  23. The implementation for .suspend uses a semaphore, which is initialized
  24. at thread creation. If the thread tries to suspend itself, we simply
  25. let it wait on the semaphore until it is unblocked by someone else
  26. who calls .Resume.
  27. If a thread is supposed to be suspended (from outside its own path of
  28. execution) on a system where the symbol LINUX is defined, two things
  29. are possible.
  30. 1) the system has the LinuxThreads pthread implementation
  31. 2) the system has NPTL as the pthread implementation.
  32. In the first case, each thread is a process on its own, which as far as
  33. know actually violates posix with respect to signal handling.
  34. But we can detect this case, because getpid(2) will
  35. return a different PID for each thread. In that case, sending SIGSTOP
  36. to the PID associated with a thread will actually stop that thread
  37. only.
  38. In the second case, this is not possible. But getpid(2) returns the same
  39. PID across all threads, which is detected, and TThread.Suspend() does
  40. nothing in that case. This should probably be changed, but I know of
  41. no way to suspend a thread when using NPTL.
  42. If the symbol LINUX is not defined, then the unimplemented
  43. function SuspendThread is called.
  44. Johannes Berg <[email protected]>, Sunday, November 16 2003
  45. }
  46. // ========== semaphore stuff ==========
  47. {
  48. I don't like this. It eats up 2 filedescriptors for each thread,
  49. and those are a limited resource. If you have a server programm
  50. handling client connections (one per thread) it will not be able
  51. to handle many if we use 2 fds already for internal structures.
  52. However, right now I don't see a better option unless some sem_*
  53. functions are added to systhrds.
  54. I encapsulated all used functions here to make it easier to
  55. change them completely.
  56. }
  57. function SemaphoreInit: Pointer;
  58. begin
  59. SemaphoreInit := GetMem(SizeOf(TFilDes));
  60. fppipe(PFilDes(SemaphoreInit)^);
  61. end;
  62. procedure SemaphoreWait(const FSem: Pointer);
  63. var
  64. b: byte;
  65. begin
  66. fpread(PFilDes(FSem)^[0], b, 1);
  67. end;
  68. procedure SemaphorePost(const FSem: Pointer);
  69. begin
  70. fpwrite(PFilDes(FSem)^[1], #0, 1);
  71. end;
  72. procedure SemaphoreDestroy(const FSem: Pointer);
  73. begin
  74. fpclose(PFilDes(FSem)^[0]);
  75. fpclose(PFilDes(FSem)^[1]);
  76. FreeMemory(FSem);
  77. end;
  78. // =========== semaphore end ===========
  79. var
  80. ThreadsInited: boolean = false;
  81. {$IFDEF LINUX}
  82. GMainPID: LongInt = 0;
  83. {$ENDIF}
  84. const
  85. // stupid, considering its not even implemented...
  86. Priorities: array [TThreadPriority] of Integer =
  87. (-20,-19,-10,0,9,18,19);
  88. procedure InitThreads;
  89. begin
  90. if not ThreadsInited then begin
  91. ThreadsInited := true;
  92. {$IFDEF LINUX}
  93. GMainPid := fpgetpid();
  94. {$ENDIF}
  95. end;
  96. end;
  97. procedure DoneThreads;
  98. begin
  99. ThreadsInited := false;
  100. end;
  101. { ok, so this is a hack, but it works nicely. Just never use
  102. a multiline argument with WRITE_DEBUG! }
  103. {$MACRO ON}
  104. {$IFDEF DEBUG_MT}
  105. {$define WRITE_DEBUG := writeln} // actually write something
  106. {$ELSE}
  107. {$define WRITE_DEBUG := //} // just comment out those lines
  108. {$ENDIF}
  109. function ThreadFunc(parameter: Pointer): LongInt; cdecl;
  110. var
  111. LThread: TThread;
  112. c: char;
  113. begin
  114. WRITE_DEBUG('ThreadFunc is here...');
  115. LThread := TThread(parameter);
  116. {$IFDEF LINUX}
  117. // save the PID of the "thread"
  118. // this is different from the PID of the main thread if
  119. // the LinuxThreads implementation is used
  120. LThread.FPid := fpgetpid();
  121. {$ENDIF}
  122. WRITE_DEBUG('thread initing, parameter = ', LongInt(LThread));
  123. try
  124. if LThread.FInitialSuspended then begin
  125. SemaphoreWait(LThread.FSem);
  126. if not LThread.FSuspended then begin
  127. LThread.FInitialSuspended := false;
  128. WRITE_DEBUG('going into LThread.Execute');
  129. LThread.Execute;
  130. end;
  131. end else begin
  132. WRITE_DEBUG('going into LThread.Execute');
  133. LThread.Execute;
  134. end;
  135. except
  136. on e: exception do begin
  137. WRITE_DEBUG('got exception: ',e.message);
  138. LThread.FFatalException := TObject(AcquireExceptionObject);
  139. // not sure if we should really do this...
  140. // but .Destroy was called, so why not try FreeOnTerminate?
  141. if e is EThreadDestroyCalled then LThread.FFreeOnTerminate := true;
  142. end;
  143. end;
  144. WRITE_DEBUG('thread done running');
  145. Result := LThread.FReturnValue;
  146. WRITE_DEBUG('Result is ',Result);
  147. LThread.FFinished := True;
  148. LThread.DoTerminate;
  149. if LThread.FreeOnTerminate then begin
  150. WRITE_DEBUG('Thread should be freed');
  151. LThread.Free;
  152. WRITE_DEBUG('Thread freed');
  153. end;
  154. WRITE_DEBUG('thread func exiting');
  155. end;
  156. { TThread }
  157. constructor TThread.Create(CreateSuspended: Boolean);
  158. begin
  159. // lets just hope that the user doesn't create a thread
  160. // via BeginThread and creates the first TThread Object in there!
  161. InitThreads;
  162. inherited Create;
  163. FSem := SemaphoreInit;
  164. FSuspended := CreateSuspended;
  165. FSuspendedExternal := false;
  166. FInitialSuspended := CreateSuspended;
  167. FFatalException := nil;
  168. WRITE_DEBUG('creating thread, self = ',longint(self));
  169. FHandle:= BeginThread(@ThreadFunc, Pointer(Self), FThreadID);
  170. WRITE_DEBUG('TThread.Create done');
  171. end;
  172. destructor TThread.Destroy;
  173. begin
  174. if FThreadID = GetCurrentThreadID then begin
  175. raise EThreadDestroyCalled.Create('A thread cannot destroy itself except by setting FreeOnTerminate and leaving!');
  176. end;
  177. // if someone calls .Free on a thread with
  178. // FreeOnTerminate, then don't crash!
  179. FFreeOnTerminate := false;
  180. if not FFinished and not FSuspended then begin
  181. Terminate;
  182. WaitFor;
  183. end;
  184. if (FInitialSuspended) then begin
  185. // thread was created suspended but never woken up.
  186. SemaphorePost(FSem);
  187. WaitFor;
  188. end;
  189. FFatalException.Free;
  190. FFatalException := nil;
  191. SemaphoreDestroy(FSem);
  192. inherited Destroy;
  193. end;
  194. procedure TThread.SetSuspended(Value: Boolean);
  195. begin
  196. if Value <> FSuspended then
  197. if Value then
  198. Suspend
  199. else
  200. Resume;
  201. end;
  202. procedure TThread.Suspend;
  203. begin
  204. if not FSuspended then begin
  205. if FThreadID = GetCurrentThreadID then begin
  206. FSuspended := true;
  207. SemaphoreWait(FSem);
  208. end else begin
  209. FSuspendedExternal := true;
  210. {$IFDEF LINUX}
  211. // naughty hack if the user doesn't have Linux with NPTL...
  212. // in that case, the PID of threads will not be identical
  213. // to the other threads, which means that our thread is a normal
  214. // process that we can suspend via SIGSTOP...
  215. // this violates POSIX, but is the way it works on the
  216. // LinuxThreads pthread implementation. Not with NPTL, but in that case
  217. // getpid(2) also behaves properly and returns the same PID for
  218. // all threads. Thats actually (FINALLY!) native thread support :-)
  219. if FPid <> GMainPID then begin
  220. FSuspended := true;
  221. fpkill(FPid, SIGSTOP);
  222. end;
  223. {$ELSE}
  224. SuspendThread(FHandle);
  225. {$ENDIF}
  226. end;
  227. end;
  228. end;
  229. procedure TThread.Resume;
  230. begin
  231. if (not FSuspendedExternal) then begin
  232. if FSuspended then begin
  233. FSuspended := False;
  234. SemaphorePost(FSem);
  235. end;
  236. end else begin
  237. FSuspendedExternal := false;
  238. ResumeThread(FHandle);
  239. end;
  240. end;
  241. procedure TThread.Terminate;
  242. begin
  243. FTerminated := True;
  244. end;
  245. function TThread.WaitFor: Integer;
  246. begin
  247. WRITE_DEBUG('waiting for thread ',FHandle);
  248. WaitFor := WaitForThreadTerminate(FHandle, 0);
  249. WRITE_DEBUG('thread terminated');
  250. end;
  251. procedure TThread.CallOnTerminate;
  252. begin
  253. // no need to check if FOnTerminate <> nil, because
  254. // thats already done in DoTerminate
  255. FOnTerminate(self);
  256. end;
  257. procedure TThread.DoTerminate;
  258. begin
  259. if Assigned(FOnTerminate) then
  260. Synchronize(@CallOnTerminate);
  261. end;
  262. function TThread.GetPriority: TThreadPriority;
  263. var
  264. P: Integer;
  265. I: TThreadPriority;
  266. begin
  267. P := ThreadGetPriority(FHandle);
  268. Result := tpNormal;
  269. for I := Low(TThreadPriority) to High(TThreadPriority) do
  270. if Priorities[I] = P then
  271. Result := I;
  272. end;
  273. procedure TThread.SetPriority(Value: TThreadPriority);
  274. begin
  275. ThreadSetPriority(FHandle, Priorities[Value]);
  276. end;
  277. {
  278. $Log: tthread.inc,v $
  279. Revision 1.5 2005/03/01 20:38:49 jonas
  280. * fixed web bug 3387: if one called resume right after creating a
  281. suspended thread, it was possible that resume was executed before
  282. that thread had completed its initialisation in BeginThread ->
  283. FInitialSuspended was set to false in resume and nevertheless a
  284. semafore was posted
  285. * second problem fixed: set FSuspended to false before waking up the
  286. thread, so that it doesn't get FSuspended = true right after waking
  287. up. This should be done atomically to be completely correct though.
  288. Revision 1.4 2005/02/25 21:41:09 florian
  289. * generic tthread.synchronize
  290. * delphi compatible wakemainthread
  291. Revision 1.3 2005/02/14 17:13:30 peter
  292. * truncate log
  293. }