tthread.inc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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. CurrentTM: TThreadManager;
  41. const
  42. // stupid, considering its not even implemented...
  43. Priorities: array [TThreadPriority] of Integer =
  44. (-20,-19,-10,0,9,18,19);
  45. procedure InitThreads;
  46. begin
  47. { This is not thread safe, but it doesn't matter if this is executed }
  48. { multiple times. Conversely, if one thread goes by this without the }
  49. { operation having been finished by another thread already, it will }
  50. { use an uninitialised thread manager -> leave as it is }
  51. if not ThreadsInited then
  52. begin
  53. GetThreadManager(CurrentTM);
  54. {$ifdef FPC_HAS_MEMBAR}
  55. { however, we have to ensure that a thread never sees ThreadsInited }
  56. { as true while CurrentTM hasn't been initialised yet }
  57. WriteBarrier;
  58. ThreadsInited := True;
  59. {$endif}
  60. end
  61. else
  62. { See double checked lock example at }
  63. { http://ridiculousfish.com/blog/archives/2007/02/17/barrier }
  64. ReadDependencyBarrier;
  65. end;
  66. procedure DoneThreads;
  67. begin
  68. ThreadsInited := false;
  69. end;
  70. function ThreadFunc(parameter: Pointer): ptrint;
  71. var
  72. LThread: TThread;
  73. LFreeOnTerminate: boolean;
  74. {$ifdef DEBUG_MT}
  75. lErrorAddr, lErrorBase: Pointer;
  76. {$endif}
  77. begin
  78. WRITE_DEBUG('ThreadFunc is here...');
  79. LThread := TThread(parameter);
  80. WRITE_DEBUG('thread initing, parameter = ', ptruint(LThread));
  81. try
  82. // wait until AfterConstruction has been called, so we cannot
  83. // free ourselves before TThread.Create has finished
  84. // (since that one may check our VTM in case of $R+, and
  85. // will call the AfterConstruction method in all cases)
  86. // LThread.Suspend;
  87. WRITE_DEBUG('AfterConstruction should have been called for ',ptruint(lthread));
  88. if LThread.FInitialSuspended then
  89. begin
  90. WRITE_DEBUG('thread ', ptruint(LThread), ' waiting for semaphore ', ptruint(LThread.FSem));
  91. CurrentTM.SemaphoreWait(LThread.FSem);
  92. if not(LThread.FTerminated) then
  93. begin
  94. if not LThread.FSuspended then
  95. begin
  96. LThread.FInitialSuspended := false;
  97. WRITE_DEBUG('going into LThread.Execute');
  98. LThread.Execute;
  99. end
  100. else
  101. WRITE_DEBUG('thread ', ptruint(LThread), ' initially created suspended, resumed, but still suspended?!');
  102. end
  103. else
  104. WRITE_DEBUG('initially created suspended, but already terminated');
  105. end
  106. else
  107. begin
  108. LThread.FSuspendedInternal := true;
  109. WRITE_DEBUG('waiting for SuspendedInternal - ', LThread.ClassName);
  110. CurrentTM.SemaphoreWait(LThread.FSem);
  111. WRITE_DEBUG('going into LThread.Execute - ', LThread.ClassName);
  112. LThread.Execute;
  113. end;
  114. except
  115. on e: exception do begin
  116. LThread.FFatalException := TObject(AcquireExceptionObject);
  117. {$ifdef DEBUG_MT}
  118. lErrorAddr:=ExceptAddr;
  119. lErrorBase:=ExceptFrames^;
  120. writeln(stderr,'Exception caught in thread $',hexstr(LThread),
  121. ' at $',hexstr(lErrorAddr));
  122. writeln(stderr,BackTraceStrFunc(lErrorAddr));
  123. dump_stack(stderr,lErrorBase);
  124. writeln(stderr);
  125. {$endif}
  126. // not sure if we should really do this...
  127. // but .Destroy was called, so why not try FreeOnTerminate?
  128. if e is EThreadDestroyCalled then LThread.FFreeOnTerminate := true;
  129. end;
  130. end;
  131. WRITE_DEBUG('thread done running');
  132. Result := LThread.FReturnValue;
  133. WRITE_DEBUG('Result is ',Result);
  134. LFreeOnTerminate := LThread.FreeOnTerminate;
  135. LThread.DoTerminate;
  136. LThread.FFinished := True;
  137. if LFreeOnTerminate then
  138. begin
  139. WRITE_DEBUG('Thread ',ptruint(lthread),' should be freed');
  140. LThread.Free;
  141. WRITE_DEBUG('Thread freed');
  142. WRITE_DEBUG('thread func calling EndThread');
  143. // we can never come here if the thread has already been joined, because
  144. // this function is the thread's main function (so it would have terminated
  145. // already in case it was joined)
  146. EndThread(Result);
  147. end
  148. else
  149. begin
  150. FlushThread;
  151. end;
  152. end;
  153. { TThread }
  154. constructor TThread.Create(CreateSuspended: Boolean;
  155. const StackSize: SizeUInt = DefaultStackSize);
  156. begin
  157. // lets just hope that the user doesn't create a thread
  158. // via BeginThread and creates the first TThread Object in there!
  159. InitThreads;
  160. inherited Create;
  161. FSem := CurrentTM.SemaphoreInit();
  162. if FSem = nil then
  163. raise EThread.create('Semaphore init failed (possibly too many concurrent threads)');
  164. WRITE_DEBUG('thread ', ptruint(self), ' created semaphore ', ptruint(FSem));
  165. FSuspended := CreateSuspended;
  166. FSuspendedExternal := false;
  167. FThreadReaped := false;
  168. FInitialSuspended := CreateSuspended;
  169. FFatalException := nil;
  170. FSuspendedInternal := not CreateSuspended;
  171. WRITE_DEBUG('creating thread, self = ',longint(self));
  172. FHandle:= BeginThread(@ThreadFunc, Pointer(Self), FThreadID, StackSize);
  173. if FHandle = TThreadID(0) then
  174. raise EThread.create('Failed to create new thread');
  175. WRITE_DEBUG('TThread.Create done, fhandle = ', ptruint(fhandle));
  176. end;
  177. destructor TThread.Destroy;
  178. begin
  179. if (FSem = nil) then
  180. { exception in constructor }
  181. begin
  182. inherited destroy;
  183. exit;
  184. end;
  185. if (FHandle = TThreadID(0)) then
  186. { another exception in constructor }
  187. begin
  188. CurrentTM.SemaphoreDestroy(FSem);
  189. inherited destroy;
  190. exit;
  191. end;
  192. if (FThreadID = GetCurrentThreadID) then
  193. begin
  194. if not(FFreeOnTerminate) and not FFinished then
  195. raise EThreadDestroyCalled.Create('A thread cannot destroy itself except by setting FreeOnTerminate and leaving!');
  196. FFreeOnTerminate := false;
  197. end
  198. else
  199. begin
  200. // if someone calls .Free on a thread with not(FreeOnTerminate), there
  201. // is no problem. Otherwise, FreeOnTerminate must be set to false so
  202. // when ThreadFunc exits the main runloop, it does not try to Free
  203. // itself again
  204. FFreeOnTerminate := false;
  205. { you can't join yourself, so only for FThreadID<>GetCurrentThreadID }
  206. { and you can't join twice -> make sure we didn't join already }
  207. if not FThreadReaped then
  208. begin
  209. Terminate;
  210. if (FSuspendedInternal or FInitialSuspended) then
  211. Resume;
  212. WaitFor;
  213. end;
  214. end;
  215. CurrentTM.SemaphoreDestroy(FSem);
  216. FFatalException.Free;
  217. FFatalException := nil;
  218. { threadvars have been released by cthreads.ThreadMain -> DoneThread, or }
  219. { or will be released (in case of FFreeOnTerminate) after this destructor }
  220. { has exited by ThreadFunc->EndThread->cthreads.CEndThread->DoneThread) }
  221. inherited Destroy;
  222. end;
  223. procedure TThread.SetSuspended(Value: Boolean);
  224. begin
  225. if Value <> FSuspended then
  226. if Value then
  227. Suspend
  228. else
  229. Resume;
  230. end;
  231. procedure TThread.Suspend;
  232. begin
  233. if FThreadID = GetCurrentThreadID then
  234. begin
  235. if not FSuspended and
  236. (InterLockedExchange(longint(FSuspended),longint(longbool(true))) = longint(longbool(false))) then
  237. CurrentTM.SemaphoreWait(FSem)
  238. end
  239. else
  240. begin
  241. 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');
  242. // FSuspendedExternal := true;
  243. // SuspendThread(FHandle);
  244. end;
  245. end;
  246. procedure TThread.Resume;
  247. begin
  248. if FSuspendedInternal and (InterLockedExchange(longint(FSuspendedInternal),ord(false)) = longint(longbool(true))) then
  249. begin
  250. WRITE_DEBUG('resuming thread after TThread construction',ptruint(self));
  251. CurrentTM.SemaphorePost(FSem);
  252. end
  253. else if (not FSuspendedExternal) then
  254. begin
  255. if FSuspended and
  256. { don't compare with ord(true) or ord(longbool(true)), }
  257. { becaue a longbool's "true" value is anyting <> false }
  258. (InterLockedExchange(longint(FSuspended),longint(false)) <> longint(longbool(false))) then
  259. begin
  260. WRITE_DEBUG('resuming ',ptruint(self));
  261. CurrentTM.SemaphorePost(FSem);
  262. end
  263. end
  264. else
  265. begin
  266. raise EThread.create('External suspending is not supported under *nix/posix, so trying to resume from from an external suspension should never happen');
  267. // FSuspendedExternal := false;
  268. // ResumeThread(FHandle);
  269. end;
  270. end;
  271. procedure TThread.Terminate;
  272. begin
  273. FTerminated := True;
  274. end;
  275. function TThread.WaitFor: Integer;
  276. begin
  277. WRITE_DEBUG('waiting for thread ',ptruint(FHandle));
  278. If (MainThreadID=GetCurrentThreadID) then
  279. {
  280. FFinished is set after DoTerminate, which does a synchronize of OnTerminate,
  281. so make sure synchronize works (or indeed any other synchronize that may be
  282. in progress)
  283. }
  284. While not FFinished do
  285. CheckSynchronize(100);
  286. WaitFor := WaitForThreadTerminate(FHandle, 0);
  287. { should actually check for errors in WaitForThreadTerminate, but no }
  288. { error api is defined for that function }
  289. FThreadReaped:=true;
  290. WRITE_DEBUG('thread terminated');
  291. end;
  292. procedure TThread.CallOnTerminate;
  293. begin
  294. // no need to check if FOnTerminate <> nil, because
  295. // thats already done in DoTerminate
  296. FOnTerminate(self);
  297. end;
  298. procedure TThread.DoTerminate;
  299. begin
  300. if Assigned(FOnTerminate) then
  301. Synchronize(@CallOnTerminate);
  302. end;
  303. function TThread.GetPriority: TThreadPriority;
  304. var
  305. P: Integer;
  306. I: TThreadPriority;
  307. begin
  308. P := ThreadGetPriority(FHandle);
  309. Result := tpNormal;
  310. for I := Low(TThreadPriority) to High(TThreadPriority) do
  311. if Priorities[I] = P then
  312. Result := I;
  313. end;
  314. procedure TThread.SetPriority(Value: TThreadPriority);
  315. begin
  316. ThreadSetPriority(FHandle, Priorities[Value]);
  317. end;