tthread.inc 10 KB

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