tthread.inc 10 KB

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