tthread.inc 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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. WRITE_DEBUG('thread func calling EndThread');
  109. // we can never come here if the thread has already been joined, because
  110. // this function is the thread's main function (so it would have terminated
  111. // already in case it was joined)
  112. EndThread(Result);
  113. end
  114. else
  115. begin
  116. FlushThread;
  117. end;
  118. end;
  119. { TThread }
  120. constructor TThread.Create(CreateSuspended: Boolean;
  121. const StackSize: SizeUInt = DefaultStackSize);
  122. begin
  123. // lets just hope that the user doesn't create a thread
  124. // via BeginThread and creates the first TThread Object in there!
  125. InitThreads;
  126. inherited Create;
  127. FSem := CurrentTM.SemaphoreInit();
  128. if FSem = nil then
  129. raise EThread.create('Semaphore init failed (possibly too many concurrent threads)');
  130. FSuspended := CreateSuspended;
  131. FSuspendedExternal := false;
  132. FThreadReaped := false;
  133. FInitialSuspended := CreateSuspended;
  134. FFatalException := nil;
  135. WRITE_DEBUG('creating thread, self = ',longint(self));
  136. FHandle:= BeginThread(@ThreadFunc, Pointer(Self), FThreadID, StackSize);
  137. if FHandle = TThreadID(0) then
  138. raise EThread.create('Failed to create new thread');
  139. WRITE_DEBUG('TThread.Create done, fhandle = ', ptrint(fhandle));
  140. end;
  141. destructor TThread.Destroy;
  142. begin
  143. if (FSem = nil) then
  144. { exception in constructor }
  145. begin
  146. inherited destroy;
  147. exit;
  148. end;
  149. if (FHandle = TThreadID(0)) then
  150. { another exception in constructor }
  151. begin
  152. CurrentTM.SemaphoreDestroy(FSem);
  153. inherited destroy;
  154. exit;
  155. end;
  156. if (FThreadID = GetCurrentThreadID) then
  157. begin
  158. if not(FFreeOnTerminate) and not FFinished then
  159. raise EThreadDestroyCalled.Create('A thread cannot destroy itself except by setting FreeOnTerminate and leaving!');
  160. FFreeOnTerminate := false;
  161. end
  162. else
  163. begin
  164. // if someone calls .Free on a thread with not(FreeOnTerminate), there
  165. // is no problem. Otherwise, FreeOnTerminate must be set to false so
  166. // when ThreadFunc exits the main runloop, it does not try to Free
  167. // itself again
  168. FFreeOnTerminate := false;
  169. { you can't join yourself, so only for FThreadID<>GetCurrentThreadID }
  170. { and you can't join twice -> make sure we didn't join already }
  171. if not FThreadReaped then
  172. begin
  173. Terminate;
  174. if (FInitialSuspended) then
  175. Resume;
  176. WaitFor;
  177. end;
  178. end;
  179. CurrentTM.SemaphoreDestroy(FSem);
  180. FFatalException.Free;
  181. FFatalException := nil;
  182. { threadvars have been released by cthreads.ThreadMain -> DoneThread, or }
  183. { or will be released (in case of FFreeOnTerminate) after this destructor }
  184. { has exited by ThreadFunc->EndThread->cthreads.CEndThread->DoneThread) }
  185. inherited Destroy;
  186. end;
  187. procedure TThread.SetSuspended(Value: Boolean);
  188. begin
  189. if Value <> FSuspended then
  190. if Value then
  191. Suspend
  192. else
  193. Resume;
  194. end;
  195. procedure TThread.Suspend;
  196. begin
  197. if FThreadID = GetCurrentThreadID then
  198. begin
  199. if not FSuspended and
  200. (InterLockedExchange(longint(FSuspended),ord(true)) = ord(false)) then
  201. CurrentTM.SemaphoreWait(FSem)
  202. end
  203. else
  204. begin
  205. Raise EThread.create('Suspending one thread from inside another one is unsupported (because it is unsafe and deadlock prone) by *nix and posix operating systems');
  206. // FSuspendedExternal := true;
  207. // SuspendThread(FHandle);
  208. end;
  209. end;
  210. procedure TThread.Resume;
  211. begin
  212. if (not FSuspendedExternal) then
  213. begin
  214. if FSuspended and
  215. (InterLockedExchange(longint(FSuspended),ord(false)) = ord(true)) then
  216. begin
  217. WRITE_DEBUG('resuming ',ptrint(self));
  218. CurrentTM.SemaphorePost(FSem);
  219. end
  220. end
  221. else
  222. begin
  223. raise EThread.create('External suspending is not supported under *nix/posix, so trying to resume from from an external suspension should never happen');
  224. // FSuspendedExternal := false;
  225. // ResumeThread(FHandle);
  226. end;
  227. end;
  228. procedure TThread.Terminate;
  229. begin
  230. FTerminated := True;
  231. end;
  232. function TThread.WaitFor: Integer;
  233. begin
  234. WRITE_DEBUG('waiting for thread ',ptrint(FHandle));
  235. WaitFor := WaitForThreadTerminate(FHandle, 0);
  236. { should actually check for errors in WaitForThreadTerminate, but no }
  237. { error api is defined for that function }
  238. FThreadReaped:=true;
  239. WRITE_DEBUG('thread terminated');
  240. end;
  241. procedure TThread.CallOnTerminate;
  242. begin
  243. // no need to check if FOnTerminate <> nil, because
  244. // thats already done in DoTerminate
  245. FOnTerminate(self);
  246. end;
  247. procedure TThread.DoTerminate;
  248. begin
  249. if Assigned(FOnTerminate) then
  250. Synchronize(@CallOnTerminate);
  251. end;
  252. function TThread.GetPriority: TThreadPriority;
  253. var
  254. P: Integer;
  255. I: TThreadPriority;
  256. begin
  257. P := ThreadGetPriority(FHandle);
  258. Result := tpNormal;
  259. for I := Low(TThreadPriority) to High(TThreadPriority) do
  260. if Priorities[I] = P then
  261. Result := I;
  262. end;
  263. procedure TThread.SetPriority(Value: TThreadPriority);
  264. begin
  265. ThreadSetPriority(FHandle, Priorities[Value]);
  266. end;