2
0

tthread.inc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. CurrentThreadVar := LThread;
  98. WRITE_DEBUG('going into LThread.Execute');
  99. LThread.Execute;
  100. end
  101. else
  102. WRITE_DEBUG('thread ', ptruint(LThread), ' initially created suspended, resumed, but still suspended?!');
  103. end
  104. else
  105. WRITE_DEBUG('initially created suspended, but already terminated');
  106. end
  107. else
  108. begin
  109. LThread.FSuspendedInternal := true;
  110. WRITE_DEBUG('waiting for SuspendedInternal - ', LThread.ClassName);
  111. CurrentTM.SemaphoreWait(LThread.FSem);
  112. CurrentThreadVar := LThread;
  113. WRITE_DEBUG('going into LThread.Execute - ', LThread.ClassName);
  114. LThread.Execute;
  115. end;
  116. except
  117. on e: exception do begin
  118. LThread.FFatalException := TObject(AcquireExceptionObject);
  119. {$ifdef DEBUG_MT}
  120. lErrorAddr:=ExceptAddr;
  121. lErrorBase:=ExceptFrames^;
  122. writeln(stderr,'Exception caught in thread $',hexstr(LThread),
  123. ' at $',hexstr(lErrorAddr));
  124. writeln(stderr,BackTraceStrFunc(lErrorAddr));
  125. dump_stack(stderr,lErrorBase);
  126. writeln(stderr);
  127. {$endif}
  128. // not sure if we should really do this...
  129. // but .Destroy was called, so why not try FreeOnTerminate?
  130. if e is EThreadDestroyCalled then LThread.FFreeOnTerminate := true;
  131. end;
  132. end;
  133. WRITE_DEBUG('thread done running');
  134. Result := LThread.FReturnValue;
  135. WRITE_DEBUG('Result is ',Result);
  136. LFreeOnTerminate := LThread.FreeOnTerminate;
  137. LThread.DoTerminate;
  138. LThread.FFinished := True;
  139. if LFreeOnTerminate then
  140. begin
  141. WRITE_DEBUG('Thread ',ptruint(lthread),' should be freed');
  142. LThread.Free;
  143. WRITE_DEBUG('Thread freed');
  144. WRITE_DEBUG('thread func calling EndThread');
  145. // we can never come here if the thread has already been joined, because
  146. // this function is the thread's main function (so it would have terminated
  147. // already in case it was joined)
  148. EndThread(Result);
  149. end
  150. else
  151. begin
  152. FlushThread;
  153. end;
  154. end;
  155. { TThread }
  156. procedure TThread.SysCreate(CreateSuspended: Boolean;
  157. const StackSize: SizeUInt);
  158. begin
  159. // lets just hope that the user doesn't create a thread
  160. // via BeginThread and creates the first TThread Object in there!
  161. InitThreads;
  162. FSem := CurrentTM.SemaphoreInit();
  163. if FSem = pointer(-1) then
  164. raise EThread.create('Semaphore init failed (possibly too many concurrent threads)');
  165. WRITE_DEBUG('thread ', ptruint(self), ' created semaphore ', ptruint(FSem));
  166. FSuspended := CreateSuspended;
  167. FSuspendedExternal := false;
  168. FThreadReaped := false;
  169. FInitialSuspended := CreateSuspended;
  170. FFatalException := nil;
  171. FSuspendedInternal := not CreateSuspended;
  172. WRITE_DEBUG('creating thread, self = ',longint(self));
  173. FHandle:= BeginThread(@ThreadFunc, Pointer(Self), FThreadID, StackSize);
  174. if FHandle = TThreadID(0) then
  175. raise EThread.create('Failed to create new thread');
  176. WRITE_DEBUG('TThread.Create done, fhandle = ', ptruint(fhandle));
  177. end;
  178. procedure TThread.SysDestroy;
  179. begin
  180. if (FSem = nil) then
  181. { exception in constructor }
  182. exit;
  183. if (FHandle = TThreadID(0)) then
  184. { another exception in constructor }
  185. begin
  186. CurrentTM.SemaphoreDestroy(FSem);
  187. exit;
  188. end;
  189. if (FThreadID = GetCurrentThreadID) then
  190. begin
  191. if not(FFreeOnTerminate) and not FFinished then
  192. raise EThreadDestroyCalled.Create('A thread cannot destroy itself except by setting FreeOnTerminate and leaving!');
  193. FFreeOnTerminate := false;
  194. end
  195. else
  196. begin
  197. // if someone calls .Free on a thread with not(FreeOnTerminate), there
  198. // is no problem. Otherwise, FreeOnTerminate must be set to false so
  199. // when ThreadFunc exits the main runloop, it does not try to Free
  200. // itself again
  201. FFreeOnTerminate := false;
  202. { you can't join yourself, so only for FThreadID<>GetCurrentThreadID }
  203. { and you can't join twice -> make sure we didn't join already }
  204. if not FThreadReaped then
  205. begin
  206. Terminate;
  207. if (FSuspendedInternal or FInitialSuspended) then
  208. Resume;
  209. WaitFor;
  210. end;
  211. end;
  212. CurrentTM.SemaphoreDestroy(FSem);
  213. FFatalException.Free;
  214. FFatalException := nil;
  215. { threadvars have been released by cthreads.ThreadMain -> DoneThread, or }
  216. { or will be released (in case of FFreeOnTerminate) after this destructor }
  217. { has exited by ThreadFunc->EndThread->cthreads.CEndThread->DoneThread) }
  218. end;
  219. procedure TThread.SetSuspended(Value: Boolean);
  220. begin
  221. if Value <> FSuspended then
  222. if Value then
  223. Suspend
  224. else
  225. Resume;
  226. end;
  227. procedure TThread.Suspend;
  228. begin
  229. if FThreadID = GetCurrentThreadID then
  230. begin
  231. if not FSuspended and
  232. (InterLockedExchange(longint(FSuspended),longint(longbool(true))) = longint(longbool(false))) then
  233. CurrentTM.SemaphoreWait(FSem)
  234. end
  235. else
  236. begin
  237. 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');
  238. // FSuspendedExternal := true;
  239. // SuspendThread(FHandle);
  240. end;
  241. end;
  242. procedure TThread.Resume;
  243. begin
  244. if FSuspendedInternal and (InterLockedExchange(longint(FSuspendedInternal),ord(false)) = longint(longbool(true))) then
  245. begin
  246. WRITE_DEBUG('resuming thread after TThread construction',ptruint(self));
  247. CurrentTM.SemaphorePost(FSem);
  248. end
  249. else if (not FSuspendedExternal) then
  250. begin
  251. if FSuspended and
  252. { don't compare with ord(true) or ord(longbool(true)), }
  253. { becaue a longbool's "true" value is anyting <> false }
  254. (InterLockedExchange(longint(FSuspended),longint(false)) <> longint(longbool(false))) then
  255. begin
  256. WRITE_DEBUG('resuming ',ptruint(self));
  257. CurrentTM.SemaphorePost(FSem);
  258. end
  259. end
  260. else
  261. begin
  262. raise EThread.create('External suspending is not supported under *nix/posix, so trying to resume from from an external suspension should never happen');
  263. // FSuspendedExternal := false;
  264. // ResumeThread(FHandle);
  265. end;
  266. end;
  267. procedure TThread.Terminate;
  268. begin
  269. FTerminated := True;
  270. end;
  271. function TThread.WaitFor: Integer;
  272. begin
  273. WRITE_DEBUG('waiting for thread ',ptruint(FHandle));
  274. If (MainThreadID=GetCurrentThreadID) then
  275. {
  276. FFinished is set after DoTerminate, which does a synchronize of OnTerminate,
  277. so make sure synchronize works (or indeed any other synchronize that may be
  278. in progress)
  279. }
  280. While not FFinished do
  281. CheckSynchronize(100);
  282. WaitFor := WaitForThreadTerminate(FHandle, 0);
  283. { should actually check for errors in WaitForThreadTerminate, but no }
  284. { error api is defined for that function }
  285. FThreadReaped:=true;
  286. WRITE_DEBUG('thread terminated');
  287. end;
  288. procedure TThread.CallOnTerminate;
  289. begin
  290. // no need to check if FOnTerminate <> nil, because
  291. // thats already done in DoTerminate
  292. FOnTerminate(self);
  293. end;
  294. procedure TThread.DoTerminate;
  295. begin
  296. if Assigned(FOnTerminate) then
  297. Synchronize(@CallOnTerminate);
  298. end;
  299. function TThread.GetPriority: TThreadPriority;
  300. var
  301. P: Integer;
  302. I: TThreadPriority;
  303. begin
  304. P := ThreadGetPriority(FHandle);
  305. Result := tpNormal;
  306. for I := Low(TThreadPriority) to High(TThreadPriority) do
  307. if Priorities[I] = P then
  308. Result := I;
  309. end;
  310. procedure TThread.SetPriority(Value: TThreadPriority);
  311. begin
  312. ThreadSetPriority(FHandle, Priorities[Value]);
  313. end;