tthread.inc 10 KB

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