tthread.inc 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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. {.$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 semaphore ', ptruint(LThread.FSem));
  69. SemaphoreWait(LThread.FSem);
  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. SemaphoreWait(LThread.FSem);
  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. FSem := SemaphoreInit();
  134. if FSem = pointer(-1) then
  135. raise EThread.create('Semaphore init failed (possibly too many concurrent threads)');
  136. WRITE_DEBUG('thread ', ptruint(self), ' created semaphore ', ptruint(FSem));
  137. FSuspended := CreateSuspended;
  138. FThreadReaped := false;
  139. FInitialSuspended := CreateSuspended;
  140. FFatalException := nil;
  141. FSuspendedInternal := not CreateSuspended;
  142. WRITE_DEBUG('creating thread, self = ',longint(self));
  143. FHandle:= BeginThread(@ThreadFunc, Pointer(Self), FThreadID, StackSize);
  144. if FHandle = TThreadID(0) then
  145. raise EThread.create('Failed to create new thread');
  146. WRITE_DEBUG('TThread.Create done, fhandle = ', ptruint(fhandle));
  147. end;
  148. procedure TThread.SysDestroy;
  149. begin
  150. if (FSem = nil) then
  151. { exception in constructor }
  152. exit;
  153. if (FHandle = TThreadID(0)) then
  154. { another exception in constructor }
  155. begin
  156. SemaphoreDestroy(FSem);
  157. exit;
  158. end;
  159. if (FThreadID = GetCurrentThreadID) then
  160. begin
  161. if not(FFreeOnTerminate) and not FFinished then
  162. raise EThreadDestroyCalled.Create('A thread cannot destroy itself except by setting FreeOnTerminate and leaving!');
  163. FFreeOnTerminate := false;
  164. end
  165. else
  166. begin
  167. // if someone calls .Free on a thread with not(FreeOnTerminate), there
  168. // is no problem. Otherwise, FreeOnTerminate must be set to false so
  169. // when ThreadFunc exits the main runloop, it does not try to Free
  170. // itself again
  171. FFreeOnTerminate := false;
  172. { you can't join yourself, so only for FThreadID<>GetCurrentThreadID }
  173. { and you can't join twice -> make sure we didn't join already }
  174. if not FThreadReaped then
  175. begin
  176. Terminate;
  177. if (FSuspendedInternal or FInitialSuspended) then
  178. Resume;
  179. WaitFor;
  180. end;
  181. end;
  182. SemaphoreDestroy(FSem);
  183. FFatalException.Free;
  184. FFatalException := nil;
  185. { threadvars have been released by cthreads.ThreadMain -> DoneThread, or }
  186. { or will be released (in case of FFreeOnTerminate) after this destructor }
  187. { has exited by ThreadFunc->EndThread->cthreads.CEndThread->DoneThread) }
  188. end;
  189. procedure TThread.SetSuspended(Value: Boolean);
  190. begin
  191. if Value <> FSuspended then
  192. if Value then
  193. Suspend
  194. else
  195. Resume;
  196. end;
  197. procedure TThread.Suspend;
  198. begin
  199. if FThreadID = GetCurrentThreadID then
  200. begin
  201. if not FSuspended and
  202. (InterLockedExchange(longint(FSuspended),longint(longbool(true))) = longint(longbool(false))) then
  203. SemaphoreWait(FSem)
  204. end
  205. else
  206. begin
  207. 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');
  208. end;
  209. end;
  210. procedure TThread.Resume;
  211. begin
  212. if FSuspendedInternal and (InterLockedExchange(longint(FSuspendedInternal),ord(false)) = longint(longbool(true))) then
  213. begin
  214. WRITE_DEBUG('resuming thread after TThread construction',ptruint(self));
  215. SemaphorePost(FSem);
  216. end
  217. else
  218. begin
  219. if FSuspended and
  220. { don't compare with ord(true) or ord(longbool(true)), }
  221. { becaue a longbool's "true" value is anyting <> false }
  222. (InterLockedExchange(longint(FSuspended),longint(false)) <> longint(longbool(false))) then
  223. begin
  224. WRITE_DEBUG('resuming ',ptruint(self));
  225. SemaphorePost(FSem);
  226. end
  227. end
  228. end;
  229. procedure TThread.Terminate;
  230. begin
  231. FTerminated := True;
  232. end;
  233. function TThread.WaitFor: Integer;
  234. begin
  235. WRITE_DEBUG('waiting for thread ',ptruint(FHandle));
  236. If (MainThreadID=GetCurrentThreadID) then
  237. {
  238. FFinished is set after DoTerminate, which does a synchronize of OnTerminate,
  239. so make sure synchronize works (or indeed any other synchronize that may be
  240. in progress)
  241. }
  242. While not FFinished do
  243. CheckSynchronize(100);
  244. WaitFor := WaitForThreadTerminate(FHandle, 0);
  245. { should actually check for errors in WaitForThreadTerminate, but no }
  246. { error api is defined for that function }
  247. FThreadReaped:=true;
  248. WRITE_DEBUG('thread terminated');
  249. end;
  250. procedure TThread.CallOnTerminate;
  251. begin
  252. // no need to check if FOnTerminate <> nil, because
  253. // thats already done in DoTerminate
  254. FOnTerminate(self);
  255. end;
  256. procedure TThread.DoTerminate;
  257. begin
  258. if Assigned(FOnTerminate) then
  259. Synchronize(@CallOnTerminate);
  260. end;
  261. function TThread.GetPriority: TThreadPriority;
  262. var
  263. P: Integer;
  264. I: TThreadPriority;
  265. begin
  266. P := ThreadGetPriority(FHandle);
  267. Result := tpNormal;
  268. for I := Low(TThreadPriority) to High(TThreadPriority) do
  269. if Priorities[I] = P then
  270. Result := I;
  271. end;
  272. procedure TThread.SetPriority(Value: TThreadPriority);
  273. begin
  274. ThreadSetPriority(FHandle, Priorities[Value]);
  275. end;