tthread.inc 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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. lErrorAddr, lErrorBase: Pointer;
  61. begin
  62. WRITE_DEBUG('ThreadFunc is here...');
  63. LThread := TThread(parameter);
  64. WRITE_DEBUG('thread initing, parameter = ', ptruint(LThread));
  65. try
  66. // wait until AfterConstruction has been called, so we cannot
  67. // free ourselves before TThread.Create has finished
  68. // (since that one may check our VTM in case of $R+, and
  69. // will call the AfterConstruction method in all cases)
  70. // LThread.Suspend;
  71. WRITE_DEBUG('AfterConstruction should have been called for ',ptruint(lthread));
  72. if LThread.FInitialSuspended then
  73. begin
  74. WRITE_DEBUG('thread ', ptruint(LThread), ' waiting for semaphore ', ptruint(LThread.FSem));
  75. CurrentTM.SemaphoreWait(LThread.FSem);
  76. if not(LThread.FTerminated) then
  77. begin
  78. if not LThread.FSuspended then
  79. begin
  80. LThread.FInitialSuspended := false;
  81. WRITE_DEBUG('going into LThread.Execute');
  82. LThread.Execute;
  83. end
  84. else
  85. WRITE_DEBUG('thread ', ptruint(LThread), ' initially created suspended, resumed, but still suspended?!');
  86. end
  87. else
  88. WRITE_DEBUG('initially created suspended, but already terminated');
  89. end
  90. else
  91. begin
  92. WRITE_DEBUG('going into LThread.Execute');
  93. LThread.Execute;
  94. end;
  95. except
  96. on e: exception do begin
  97. LThread.FFatalException := TObject(AcquireExceptionObject);
  98. lErrorAddr:=ExceptAddr;
  99. lErrorBase:=ExceptFrames^;
  100. writeln(stderr,'Exception caught in thread $',hexstr(LThread),
  101. ' at $',hexstr(lErrorAddr));
  102. writeln(stderr,BackTraceStrFunc(lErrorAddr));
  103. dump_stack(stderr,lErrorBase);
  104. writeln(stderr);
  105. // not sure if we should really do this...
  106. // but .Destroy was called, so why not try FreeOnTerminate?
  107. if e is EThreadDestroyCalled then LThread.FFreeOnTerminate := true;
  108. end;
  109. end;
  110. WRITE_DEBUG('thread done running');
  111. Result := LThread.FReturnValue;
  112. WRITE_DEBUG('Result is ',Result);
  113. LThread.FFinished := True;
  114. LThread.DoTerminate;
  115. if LThread.FreeOnTerminate then
  116. begin
  117. WRITE_DEBUG('Thread ',ptruint(lthread),' should be freed');
  118. LThread.Free;
  119. WRITE_DEBUG('Thread freed');
  120. WRITE_DEBUG('thread func calling EndThread');
  121. // we can never come here if the thread has already been joined, because
  122. // this function is the thread's main function (so it would have terminated
  123. // already in case it was joined)
  124. EndThread(Result);
  125. end
  126. else
  127. begin
  128. FlushThread;
  129. end;
  130. end;
  131. { TThread }
  132. constructor TThread.Create(CreateSuspended: Boolean;
  133. const StackSize: SizeUInt = DefaultStackSize);
  134. begin
  135. // lets just hope that the user doesn't create a thread
  136. // via BeginThread and creates the first TThread Object in there!
  137. InitThreads;
  138. inherited Create;
  139. FSem := CurrentTM.SemaphoreInit();
  140. if FSem = nil then
  141. raise EThread.create('Semaphore init failed (possibly too many concurrent threads)');
  142. WRITE_DEBUG('thread ', ptruint(self), ' created semaphore ', ptruint(FSem));
  143. FSuspended := CreateSuspended;
  144. FSuspendedExternal := false;
  145. FThreadReaped := false;
  146. FInitialSuspended := CreateSuspended;
  147. FFatalException := nil;
  148. WRITE_DEBUG('creating thread, self = ',longint(self));
  149. FHandle:= BeginThread(@ThreadFunc, Pointer(Self), FThreadID, StackSize);
  150. if FHandle = TThreadID(0) then
  151. raise EThread.create('Failed to create new thread');
  152. WRITE_DEBUG('TThread.Create done, fhandle = ', ptruint(fhandle));
  153. end;
  154. destructor TThread.Destroy;
  155. begin
  156. if (FSem = nil) then
  157. { exception in constructor }
  158. begin
  159. inherited destroy;
  160. exit;
  161. end;
  162. if (FHandle = TThreadID(0)) then
  163. { another exception in constructor }
  164. begin
  165. CurrentTM.SemaphoreDestroy(FSem);
  166. inherited destroy;
  167. exit;
  168. end;
  169. if (FThreadID = GetCurrentThreadID) then
  170. begin
  171. if not(FFreeOnTerminate) and not FFinished then
  172. raise EThreadDestroyCalled.Create('A thread cannot destroy itself except by setting FreeOnTerminate and leaving!');
  173. FFreeOnTerminate := false;
  174. end
  175. else
  176. begin
  177. // if someone calls .Free on a thread with not(FreeOnTerminate), there
  178. // is no problem. Otherwise, FreeOnTerminate must be set to false so
  179. // when ThreadFunc exits the main runloop, it does not try to Free
  180. // itself again
  181. FFreeOnTerminate := false;
  182. { you can't join yourself, so only for FThreadID<>GetCurrentThreadID }
  183. { and you can't join twice -> make sure we didn't join already }
  184. if not FThreadReaped then
  185. begin
  186. Terminate;
  187. if (FInitialSuspended) then
  188. Resume;
  189. WaitFor;
  190. end;
  191. end;
  192. CurrentTM.SemaphoreDestroy(FSem);
  193. FFatalException.Free;
  194. FFatalException := nil;
  195. { threadvars have been released by cthreads.ThreadMain -> DoneThread, or }
  196. { or will be released (in case of FFreeOnTerminate) after this destructor }
  197. { has exited by ThreadFunc->EndThread->cthreads.CEndThread->DoneThread) }
  198. inherited Destroy;
  199. end;
  200. procedure TThread.SetSuspended(Value: Boolean);
  201. begin
  202. if Value <> FSuspended then
  203. if Value then
  204. Suspend
  205. else
  206. Resume;
  207. end;
  208. procedure TThread.Suspend;
  209. begin
  210. if FThreadID = GetCurrentThreadID then
  211. begin
  212. if not FSuspended and
  213. (InterLockedExchange(longint(FSuspended),ord(true)) = ord(false)) then
  214. CurrentTM.SemaphoreWait(FSem)
  215. end
  216. else
  217. begin
  218. 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');
  219. // FSuspendedExternal := true;
  220. // SuspendThread(FHandle);
  221. end;
  222. end;
  223. procedure TThread.Resume;
  224. begin
  225. if (not FSuspendedExternal) then
  226. begin
  227. if FSuspended and
  228. (InterLockedExchange(longint(FSuspended),ord(false)) = ord(true)) then
  229. begin
  230. WRITE_DEBUG('resuming ',ptruint(self));
  231. CurrentTM.SemaphorePost(FSem);
  232. end
  233. end
  234. else
  235. begin
  236. raise EThread.create('External suspending is not supported under *nix/posix, so trying to resume from from an external suspension should never happen');
  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 ',ptruint(FHandle));
  248. WaitFor := WaitForThreadTerminate(FHandle, 0);
  249. { should actually check for errors in WaitForThreadTerminate, but no }
  250. { error api is defined for that function }
  251. FThreadReaped:=true;
  252. WRITE_DEBUG('thread terminated');
  253. end;
  254. procedure TThread.CallOnTerminate;
  255. begin
  256. // no need to check if FOnTerminate <> nil, because
  257. // thats already done in DoTerminate
  258. FOnTerminate(self);
  259. end;
  260. procedure TThread.DoTerminate;
  261. begin
  262. if Assigned(FOnTerminate) then
  263. Synchronize(@CallOnTerminate);
  264. end;
  265. function TThread.GetPriority: TThreadPriority;
  266. var
  267. P: Integer;
  268. I: TThreadPriority;
  269. begin
  270. P := ThreadGetPriority(FHandle);
  271. Result := tpNormal;
  272. for I := Low(TThreadPriority) to High(TThreadPriority) do
  273. if Priorities[I] = P then
  274. Result := I;
  275. end;
  276. procedure TThread.SetPriority(Value: TThreadPriority);
  277. begin
  278. ThreadSetPriority(FHandle, Priorities[Value]);
  279. end;