tthread.inc 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. {
  2. This file is part of the Free Pascal run time library.
  3. Copyright (c) 1999-2000 by Peter Vreman
  4. Copyright (c) 2006 by Jonas Maebe
  5. members of the Free Pascal development team.
  6. Generic *nix TThread implementation
  7. See the file COPYING.FPC, included in this distribution,
  8. for details about the copyright.
  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. Johannes Berg <[email protected]>, Sunday, November 16 2003
  28. }
  29. { ok, so this is a hack, but it works nicely. Just never use
  30. a multiline argument with WRITE_DEBUG! }
  31. {$MACRO ON}
  32. {$IFDEF DEBUG_MT}
  33. {$define WRITE_DEBUG := writeln} // actually write something
  34. {$ELSE}
  35. {$define WRITE_DEBUG := //} // just comment out those lines
  36. {$ENDIF}
  37. var
  38. ThreadsInited: boolean = false;
  39. CurrentTM: TThreadManager;
  40. const
  41. // stupid, considering its not even implemented...
  42. Priorities: array [TThreadPriority] of Integer =
  43. (-20,-19,-10,0,9,18,19);
  44. procedure InitThreads;
  45. begin
  46. { This is not thread safe, but it doesn't matter if this is executed }
  47. { multiple times. Conversely, if one thread goes by this without the }
  48. { operation having been finished by another thread already, it will }
  49. { use an uninitialised thread manager -> leave as it is }
  50. if not ThreadsInited then
  51. GetThreadManager(CurrentTM);
  52. end;
  53. procedure DoneThreads;
  54. begin
  55. ThreadsInited := false;
  56. end;
  57. function ThreadFunc(parameter: Pointer): ptrint;
  58. var
  59. LThread: TThread;
  60. begin
  61. WRITE_DEBUG('ThreadFunc is here...');
  62. LThread := TThread(parameter);
  63. WRITE_DEBUG('thread initing, parameter = ', ptrint(LThread));
  64. try
  65. // wait until AfterConstruction has been called, so we cannot
  66. // free ourselves before TThread.Create has finished
  67. // (since that one may check our VTM in case of $R+, and
  68. // will call the AfterConstruction method in all cases)
  69. // LThread.Suspend;
  70. WRITE_DEBUG('AfterConstruction should have been called for ',ptrint(lthread));
  71. if LThread.FInitialSuspended then
  72. begin
  73. CurrentTM.SemaphoreWait(LThread.FSem);
  74. if not(LThread.FTerminated) then
  75. begin
  76. if not LThread.FSuspended then
  77. begin
  78. LThread.FInitialSuspended := false;
  79. WRITE_DEBUG('going into LThread.Execute');
  80. LThread.Execute;
  81. end;
  82. end;
  83. end
  84. else
  85. begin
  86. WRITE_DEBUG('going into LThread.Execute');
  87. LThread.Execute;
  88. end;
  89. except
  90. on e: exception do begin
  91. WRITE_DEBUG('got exception: ',e.message);
  92. LThread.FFatalException := TObject(AcquireExceptionObject);
  93. // not sure if we should really do this...
  94. // but .Destroy was called, so why not try FreeOnTerminate?
  95. if e is EThreadDestroyCalled then LThread.FFreeOnTerminate := true;
  96. end;
  97. end;
  98. WRITE_DEBUG('thread done running');
  99. Result := LThread.FReturnValue;
  100. WRITE_DEBUG('Result is ',Result);
  101. LThread.FFinished := True;
  102. LThread.DoTerminate;
  103. if LThread.FreeOnTerminate then
  104. begin
  105. WRITE_DEBUG('Thread ',ptrint(lthread),' should be freed');
  106. LThread.Free;
  107. WRITE_DEBUG('Thread freed');
  108. // tthread.destroy already frees all things and terminates the thread
  109. // WRITE_DEBUG('thread func calling EndThread');
  110. // EndThread(Result);
  111. end
  112. else
  113. begin
  114. FlushThread;
  115. end;
  116. end;
  117. { TThread }
  118. constructor TThread.Create(CreateSuspended: Boolean;
  119. const StackSize: SizeUInt = DefaultStackSize);
  120. begin
  121. // lets just hope that the user doesn't create a thread
  122. // via BeginThread and creates the first TThread Object in there!
  123. InitThreads;
  124. inherited Create;
  125. FSem := CurrentTM.SemaphoreInit();
  126. if FSem = nil then
  127. raise EThread.create('Semaphore init failed (possibly too many concurrent threads)');
  128. FSuspended := CreateSuspended;
  129. FSuspendedExternal := false;
  130. FInitialSuspended := CreateSuspended;
  131. FFatalException := nil;
  132. WRITE_DEBUG('creating thread, self = ',longint(self));
  133. FHandle:= BeginThread(@ThreadFunc, Pointer(Self), FThreadID, StackSize);
  134. if FHandle = TThreadID(0) then
  135. raise EThread.create('Failed to create new thread');
  136. WRITE_DEBUG('TThread.Create done, fhandle = ', ptrint(fhandle));
  137. end;
  138. destructor TThread.Destroy;
  139. begin
  140. if (FSem = nil) then
  141. { exception in constructor }
  142. begin
  143. inherited destroy;
  144. exit;
  145. end;
  146. if (FHandle = TThreadID(0)) then
  147. { another exception in constructor }
  148. begin
  149. CurrentTM.SemaphoreDestroy(FSem);
  150. inherited destroy;
  151. exit;
  152. end;
  153. if (FThreadID = GetCurrentThreadID) and not(FFreeOnTerminate) and not FFinished then
  154. raise EThreadDestroyCalled.Create('A thread cannot destroy itself except by setting FreeOnTerminate and leaving!');
  155. // if someone calls .Free on a thread with
  156. // FreeOnTerminate, then don't crash!
  157. FFreeOnTerminate := false;
  158. if not FFinished then
  159. begin
  160. Terminate;
  161. if (FInitialSuspended) then
  162. Resume;
  163. WaitFor;
  164. end;
  165. CurrentTM.SemaphoreDestroy(FSem);
  166. FFatalException.Free;
  167. FFatalException := nil;
  168. { threadvars have been released by cthreads.ThreadMain -> DoneThread }
  169. inherited Destroy;
  170. end;
  171. procedure TThread.SetSuspended(Value: Boolean);
  172. begin
  173. if Value <> FSuspended then
  174. if Value then
  175. Suspend
  176. else
  177. Resume;
  178. end;
  179. procedure TThread.Suspend;
  180. begin
  181. if not FSuspended and
  182. (InterLockedExchange(longint(FSuspended),ord(true)) = ord(false)) then
  183. begin
  184. if FThreadID = GetCurrentThreadID then
  185. CurrentTM.SemaphoreWait(FSem)
  186. else
  187. begin
  188. FSuspendedExternal := true;
  189. SuspendThread(FHandle);
  190. end;
  191. end;
  192. end;
  193. procedure TThread.Resume;
  194. begin
  195. if FSuspended and
  196. (InterLockedExchange(longint(FSuspended),ord(false)) = ord(true)) then
  197. if (not FSuspendedExternal) then
  198. begin
  199. WRITE_DEBUG('resuming ',ptrint(self));
  200. CurrentTM.SemaphorePost(FSem);
  201. end
  202. else
  203. begin
  204. FSuspendedExternal := false;
  205. ResumeThread(FHandle);
  206. end;
  207. end;
  208. procedure TThread.Terminate;
  209. begin
  210. FTerminated := True;
  211. end;
  212. function TThread.WaitFor: Integer;
  213. begin
  214. WRITE_DEBUG('waiting for thread ',ptrint(FHandle));
  215. WaitFor := WaitForThreadTerminate(FHandle, 0);
  216. WRITE_DEBUG('thread terminated');
  217. end;
  218. procedure TThread.CallOnTerminate;
  219. begin
  220. // no need to check if FOnTerminate <> nil, because
  221. // thats already done in DoTerminate
  222. FOnTerminate(self);
  223. end;
  224. procedure TThread.DoTerminate;
  225. begin
  226. if Assigned(FOnTerminate) then
  227. Synchronize(@CallOnTerminate);
  228. end;
  229. function TThread.GetPriority: TThreadPriority;
  230. var
  231. P: Integer;
  232. I: TThreadPriority;
  233. begin
  234. P := ThreadGetPriority(FHandle);
  235. Result := tpNormal;
  236. for I := Low(TThreadPriority) to High(TThreadPriority) do
  237. if Priorities[I] = P then
  238. Result := I;
  239. end;
  240. procedure TThread.SetPriority(Value: TThreadPriority);
  241. begin
  242. ThreadSetPriority(FHandle, Priorities[Value]);
  243. end;