tthread.inc 9.3 KB

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