2
0

tthread.inc 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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 an RTLEvent, which is initialized
  24. at thread creation. If the thread tries to suspend itself, we simply
  25. let it wait on the Event 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. {.$DEFINE DEBUG_MT}
  32. {$MACRO ON}
  33. {$IFDEF DEBUG_MT}
  34. {$define WRITE_DEBUG := writeln} // actually write something
  35. {$ELSE}
  36. {$define WRITE_DEBUG := //} // just comment out those lines
  37. {$ENDIF}
  38. var
  39. ThreadsInited: boolean = false;
  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 DoneThreads;
  45. begin
  46. ThreadsInited := false;
  47. end;
  48. function ThreadFunc(parameter: Pointer): ptrint;
  49. var
  50. LThread: TThread;
  51. LFreeOnTerminate: boolean;
  52. {$ifdef DEBUG_MT}
  53. lErrorAddr, lErrorBase: Pointer;
  54. {$endif}
  55. begin
  56. WRITE_DEBUG('ThreadFunc is here...');
  57. LThread := TThread(parameter);
  58. WRITE_DEBUG('thread initing, parameter = ', ptruint(LThread));
  59. try
  60. // wait until AfterConstruction has been called, so we cannot
  61. // free ourselves before TThread.Create has finished
  62. // (since that one may check our VTM in case of $R+, and
  63. // will call the AfterConstruction method in all cases)
  64. // LThread.Suspend;
  65. WRITE_DEBUG('AfterConstruction should have been called for ',ptruint(lthread));
  66. if LThread.FInitialSuspended then
  67. begin
  68. WRITE_DEBUG('thread ', ptruint(LThread), ' waiting for RTLEvent ', ptruint(LThread.FSuspendEvent));
  69. RtlEventWaitFor(LThread.FSuspendEvent);
  70. if not(LThread.FTerminated) then
  71. begin
  72. if not LThread.FSuspended then
  73. begin
  74. LThread.FInitialSuspended := false;
  75. CurrentThreadVar := LThread;
  76. WRITE_DEBUG('going into LThread.Execute');
  77. LThread.Execute;
  78. end
  79. else
  80. WRITE_DEBUG('thread ', ptruint(LThread), ' initially created suspended, resumed, but still suspended?!');
  81. end
  82. else
  83. WRITE_DEBUG('initially created suspended, but already terminated');
  84. end
  85. else
  86. begin
  87. LThread.FSuspendedInternal := true;
  88. WRITE_DEBUG('waiting for SuspendedInternal - ', LThread.ClassName);
  89. RtlEventWaitFor(LThread.FSuspendEvent);
  90. CurrentThreadVar := LThread;
  91. WRITE_DEBUG('going into LThread.Execute - ', LThread.ClassName);
  92. LThread.Execute;
  93. end;
  94. except
  95. on e: exception do begin
  96. LThread.FFatalException := TObject(AcquireExceptionObject);
  97. {$ifdef DEBUG_MT}
  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. {$endif}
  106. // not sure if we should really do this...
  107. // but .Destroy was called, so why not try FreeOnTerminate?
  108. if e is EThreadDestroyCalled then LThread.FFreeOnTerminate := true;
  109. end;
  110. end;
  111. WRITE_DEBUG('thread done running');
  112. Result := LThread.FReturnValue;
  113. WRITE_DEBUG('Result is ',Result);
  114. LFreeOnTerminate := LThread.FreeOnTerminate;
  115. LThread.DoTerminate;
  116. LThread.FFinished := True;
  117. if LFreeOnTerminate then
  118. begin
  119. WRITE_DEBUG('Thread ',ptruint(lthread),' should be freed');
  120. LThread.Free;
  121. WRITE_DEBUG('Thread freed');
  122. WRITE_DEBUG('thread func calling EndThread');
  123. // we can never come here if the thread has already been joined, because
  124. // this function is the thread's main function (so it would have terminated
  125. // already in case it was joined)
  126. EndThread(Result);
  127. end;
  128. end;
  129. { TThread }
  130. procedure TThread.SysCreate(CreateSuspended: Boolean;
  131. const StackSize: SizeUInt);
  132. begin
  133. FSuspendEvent := RtlEventCreate;
  134. WRITE_DEBUG('thread ', ptruint(self), ' created RTLEvent ', ptruint(FSuspendEvent));
  135. FSuspended := CreateSuspended;
  136. FThreadReaped := false;
  137. FInitialSuspended := CreateSuspended;
  138. FFatalException := nil;
  139. FSuspendedInternal := not CreateSuspended;
  140. WRITE_DEBUG('creating thread, self = ',ptruint(self));
  141. FHandle:= BeginThread(@ThreadFunc, Pointer(Self), FThreadID, StackSize);
  142. if FHandle = TThreadID(0) then
  143. raise EThread.create('Failed to create new thread');
  144. WRITE_DEBUG('TThread.Create done, fhandle = ', ptruint(fhandle));
  145. end;
  146. procedure TThread.SysDestroy;
  147. begin
  148. if not assigned(FSuspendEvent) then
  149. { exception in constructor }
  150. exit;
  151. if (FHandle = TThreadID(0)) then
  152. { another exception in constructor }
  153. begin
  154. RtlEventDestroy(FSuspendEvent);
  155. exit;
  156. end;
  157. if (FThreadID = GetCurrentThreadID) then
  158. begin
  159. if not(FFreeOnTerminate) and not FFinished then
  160. raise EThreadDestroyCalled.Create('A thread cannot destroy itself except by setting FreeOnTerminate and leaving!');
  161. FFreeOnTerminate := false;
  162. end
  163. else
  164. begin
  165. // if someone calls .Free on a thread with not(FreeOnTerminate), there
  166. // is no problem. Otherwise, FreeOnTerminate must be set to false so
  167. // when ThreadFunc exits the main runloop, it does not try to Free
  168. // itself again
  169. FFreeOnTerminate := false;
  170. { you can't join yourself, so only for FThreadID<>GetCurrentThreadID }
  171. { and you can't join twice -> make sure we didn't join already }
  172. if not FThreadReaped then
  173. begin
  174. Terminate;
  175. if (FSuspendedInternal or FInitialSuspended) then
  176. Resume;
  177. WaitFor;
  178. end;
  179. end;
  180. RtlEventDestroy(FSuspendEvent);
  181. FFatalException.Free;
  182. FFatalException := nil;
  183. { threadvars have been released by cthreads.ThreadMain -> DoneThread, or }
  184. { or will be released (in case of FFreeOnTerminate) after this destructor }
  185. { has exited by ThreadFunc->EndThread->cthreads.CEndThread->DoneThread) }
  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),longint(longbool(true))) = longint(longbool(false))) then
  201. RtlEventWaitFor(FSuspendEvent)
  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. end;
  207. end;
  208. procedure TThread.Resume;
  209. begin
  210. if FSuspendedInternal and (InterLockedExchange(longint(FSuspendedInternal),ord(false)) = longint(longbool(true))) then
  211. begin
  212. WRITE_DEBUG('resuming thread after TThread construction',ptruint(self));
  213. RtlEventSetEvent(FSuspendEvent);
  214. end
  215. else
  216. begin
  217. if FSuspended and
  218. { don't compare with ord(true) or ord(longbool(true)), }
  219. { becaue a longbool's "true" value is anyting <> false }
  220. (InterLockedExchange(longint(FSuspended),longint(false)) <> longint(longbool(false))) then
  221. begin
  222. WRITE_DEBUG('resuming ',ptruint(self));
  223. RtlEventSetEvent(FSuspendEvent);
  224. end
  225. end
  226. end;
  227. procedure TThread.Terminate;
  228. begin
  229. FTerminated := True;
  230. TerminatedSet;
  231. end;
  232. function TThread.WaitFor: Integer;
  233. begin
  234. WRITE_DEBUG('waiting for thread ',ptruint(FHandle));
  235. If (MainThreadID=GetCurrentThreadID) then
  236. {
  237. FFinished is set after DoTerminate, which does a synchronize of OnTerminate,
  238. so make sure synchronize works (or indeed any other synchronize that may be
  239. in progress)
  240. }
  241. While not FFinished do
  242. CheckSynchronize(100);
  243. WaitFor := WaitForThreadTerminate(FHandle, 0);
  244. { should actually check for errors in WaitForThreadTerminate, but no }
  245. { error api is defined for that function }
  246. FThreadReaped:=true;
  247. WRITE_DEBUG('thread terminated');
  248. end;
  249. procedure TThread.CallOnTerminate;
  250. begin
  251. // no need to check if FOnTerminate <> nil, because
  252. // thats already done in DoTerminate
  253. FOnTerminate(self);
  254. end;
  255. procedure TThread.DoTerminate;
  256. begin
  257. if Assigned(FOnTerminate) then
  258. Synchronize(@CallOnTerminate);
  259. end;
  260. function TThread.GetPriority: TThreadPriority;
  261. var
  262. P: Integer;
  263. I: TThreadPriority;
  264. begin
  265. P := ThreadGetPriority(FHandle);
  266. Result := tpNormal;
  267. for I := Low(TThreadPriority) to High(TThreadPriority) do
  268. if Priorities[I] = P then
  269. Result := I;
  270. end;
  271. procedure TThread.SetPriority(Value: TThreadPriority);
  272. begin
  273. ThreadSetPriority(FHandle, Priorities[Value]);
  274. end;