tthread.inc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. {
  2. This file is part of the Free Component Library (FCL)
  3. Copyright (c) 1999-2000 by Peter Vreman
  4. Netware Libc TThread implementation
  5. See the file COPYING.FPC, included in this distribution,
  6. for details about the copyright.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  10. **********************************************************************}
  11. {
  12. What follows, is a short description on my implementation of TThread.
  13. Most information can also be found by reading the source and accompanying
  14. comments.
  15. A thread is created using BeginThread, which in turn calls
  16. pthread_create. So the threads here are always posix threads.
  17. Posix doesn't define anything for suspending threads as this is
  18. inherintly unsafe. Just don't suspend threads at points they cannot
  19. control. Therefore, I didn't implement .Suspend() if its called from
  20. outside the threads execution flow (except on Linux _without_ NPTL).
  21. The implementation for .suspend uses a semaphore, which is initialized
  22. at thread creation. If the thread tries to suspend itself, we simply
  23. let it wait on the semaphore until it is unblocked by someone else
  24. who calls .Resume.
  25. If a thread is supposed to be suspended (from outside its own path of
  26. execution) on a system where the symbol LINUX is defined, two things
  27. are possible.
  28. 1) the system has the LinuxThreads pthread implementation
  29. 2) the system has NPTL as the pthread implementation.
  30. In the first case, each thread is a process on its own, which as far as
  31. know actually violates posix with respect to signal handling.
  32. But we can detect this case, because getpid(2) will
  33. return a different PID for each thread. In that case, sending SIGSTOP
  34. to the PID associated with a thread will actually stop that thread
  35. only.
  36. In the second case, this is not possible. But getpid(2) returns the same
  37. PID across all threads, which is detected, and TThread.Suspend() does
  38. nothing in that case. This should probably be changed, but I know of
  39. no way to suspend a thread when using NPTL.
  40. If the symbol LINUX is not defined, then the unimplemented
  41. function SuspendThread is called.
  42. Johannes Berg <[email protected]>, Sunday, November 16 2003
  43. }
  44. // ========== semaphore stuff ==========
  45. {
  46. I don't like this. It eats up 2 filedescriptors for each thread,
  47. and those are a limited resource. If you have a server programm
  48. handling client connections (one per thread) it will not be able
  49. to handle many if we use 2 fds already for internal structures.
  50. However, right now I don't see a better option unless some sem_*
  51. functions are added to systhrds.
  52. I encapsulated all used functions here to make it easier to
  53. change them completely.
  54. }
  55. { ok, so this is a hack, but it works nicely. Just never use
  56. a multiline argument with WRITE_DEBUG! }
  57. {$MACRO ON}
  58. {$IFDEF DEBUG_MT}
  59. {$define WRITE_DEBUG := ConsolePrintf} // actually write something
  60. {$ELSE}
  61. {$define WRITE_DEBUG := //} // just comment out those lines
  62. {$ENDIF}
  63. function SemaphoreInit: Pointer;
  64. begin
  65. SemaphoreInit := GetMem(SizeOf(TFilDes));
  66. fppipe(PFilDes(SemaphoreInit)^);
  67. end;
  68. procedure SemaphoreWait(const FSem: Pointer);
  69. var
  70. b: byte;
  71. begin
  72. fpread(PFilDes(FSem)^[0], b, 1);
  73. end;
  74. procedure SemaphorePost(const FSem: Pointer);
  75. var c : char;
  76. begin
  77. c := #0;
  78. fpwrite(PFilDes(FSem)^[1], c, 1);
  79. end;
  80. procedure SemaphoreDestroy(const FSem: Pointer);
  81. begin
  82. fpclose(PFilDes(FSem)^[0]);
  83. fpclose(PFilDes(FSem)^[1]);
  84. FreeMemory(FSem);
  85. end;
  86. // =========== semaphore end ===========
  87. type
  88. PThreadRec=^TThreadRec;
  89. TThreadRec=record
  90. thread : TThread;
  91. next : PThreadRec;
  92. end;
  93. var
  94. ThreadRoot : PThreadRec;
  95. ThreadsInited : boolean = false;
  96. DisableRemoveThread : boolean;
  97. ThreadCount: longint = 0;
  98. {$IFDEF LINUX}
  99. GMainPID: LongInt = 0;
  100. {$ENDIF}
  101. const
  102. // stupid, considering its not even implemented...
  103. Priorities: array [TThreadPriority] of Integer =
  104. (-20,-19,-10,0,9,18,19);
  105. procedure InitThreads;
  106. begin
  107. if not ThreadsInited then begin
  108. ThreadsInited := true;
  109. {$IFDEF LINUX}
  110. GMainPid := fpgetpid();
  111. {$ENDIF}
  112. ThreadRoot:=nil;
  113. ThreadsInited:=true;
  114. DisableRemoveThread:=false;
  115. end;
  116. end;
  117. procedure DoneThreads;
  118. var
  119. hp,next : PThreadRec;
  120. begin
  121. DisableRemoveThread := true; {to avoid that Destroy calling RemoveThread modifies Thread List}
  122. while assigned(ThreadRoot) do
  123. begin
  124. WRITE_DEBUG('DoneThreads: calling Destroy'#13#10);
  125. ThreadRoot^.Thread.Destroy;
  126. hp:=ThreadRoot;
  127. ThreadRoot:=ThreadRoot^.Next;
  128. dispose(hp);
  129. WRITE_DEBUG('DoneThreads: called destroy, remaining threads: %d ThreadRoot: %x'#13#10,ThreadCount,longint(ThreadRoot));
  130. end;
  131. ThreadsInited:=false;
  132. end;
  133. procedure AddThread(t:TThread);
  134. var
  135. hp : PThreadRec;
  136. begin
  137. { Need to initialize threads ? }
  138. if not ThreadsInited then
  139. InitThreads;
  140. { Put thread in the linked list }
  141. new(hp);
  142. hp^.Thread:=t;
  143. hp^.next:=ThreadRoot;
  144. ThreadRoot:=hp;
  145. inc(ThreadCount);
  146. end;
  147. procedure RemoveThread(t:TThread);
  148. var
  149. lasthp,hp : PThreadRec;
  150. begin
  151. if not DisableRemoveThread then {disabled while in DoneThreads}
  152. begin
  153. hp:=ThreadRoot;
  154. lasthp:=nil;
  155. while assigned(hp) do
  156. begin
  157. if hp^.Thread=t then
  158. begin
  159. if assigned(lasthp) then
  160. lasthp^.next:=hp^.next
  161. else
  162. ThreadRoot:=hp^.next;
  163. dispose(hp);
  164. Dec(ThreadCount);
  165. if ThreadCount = 0 then ThreadsInited := false;
  166. exit;
  167. end;
  168. lasthp:=hp;
  169. hp:=hp^.next;
  170. end;
  171. end else
  172. dec(ThreadCount);
  173. end;
  174. function ThreadFunc(parameter: Pointer): LongInt;
  175. var
  176. LThread: TThread;
  177. c: char;
  178. begin
  179. WRITE_DEBUG('ThreadFunc is here...'#13#10);
  180. LThread := TThread(parameter);
  181. {$IFDEF LINUX}
  182. // save the PID of the "thread"
  183. // this is different from the PID of the main thread if
  184. // the LinuxThreads implementation is used
  185. LThread.FPid := fpgetpid();
  186. {$ENDIF}
  187. WRITE_DEBUG('thread initing, parameter = %d'#13#10, LongInt(LThread));
  188. try
  189. // wait until AfterConstruction has been called, so we cannot
  190. // free ourselves before TThread.Create has finished
  191. // (since that one may check our VTM in case of $R+, and
  192. // will call the AfterConstruction method in all cases)
  193. LThread.Suspend;
  194. if LThread.FInitialSuspended then begin
  195. LThread.Suspend;
  196. if not LThread.FInitialSuspended then begin
  197. CurrentThreadVar := LThread;
  198. WRITE_DEBUG('going into LThread.Execute'#13#10);
  199. LThread.Execute;
  200. end;
  201. end else begin
  202. CurrentThreadVar := LThread;
  203. WRITE_DEBUG('going into LThread.Execute'#13#10);
  204. LThread.Execute;
  205. end;
  206. except
  207. on e: exception do begin
  208. WRITE_DEBUG('got exception: %s'#13#10,pchar(e.message));
  209. LThread.FFatalException := TObject(AcquireExceptionObject);
  210. // not sure if we should really do this...
  211. // but .Destroy was called, so why not try FreeOnTerminate?
  212. if e is EThreadDestroyCalled then LThread.FFreeOnTerminate := true;
  213. end;
  214. end;
  215. WRITE_DEBUG('thread done running'#13#10);
  216. Result := LThread.FReturnValue;
  217. WRITE_DEBUG('Result is %d'#13#10,Result);
  218. LThread.FFinished := True;
  219. LThread.DoTerminate;
  220. if LThread.FreeOnTerminate then begin
  221. WRITE_DEBUG('Thread should be freed'#13#10);
  222. LThread.Free;
  223. WRITE_DEBUG('Thread freed'#13#10);
  224. end;
  225. WRITE_DEBUG('thread func calling EndThread'#13#10);
  226. EndThread(Result);
  227. end;
  228. { TThread }
  229. procedure TThread.SysCreate(CreateSuspended: Boolean;
  230. const StackSize: SizeUInt);
  231. begin
  232. // lets just hope that the user doesn't create a thread
  233. // via BeginThread and creates the first TThread Object in there!
  234. InitThreads;
  235. AddThread(self);
  236. FSem := SemaphoreInit;
  237. FSuspended := False;
  238. FSuspendedExternal := false;
  239. FInitialSuspended := CreateSuspended;
  240. FFatalException := nil;
  241. WRITE_DEBUG('creating thread, self = %d'#13#10,longint(self));
  242. FHandle:= BeginThread(@ThreadFunc, Pointer(Self), FThreadID, StackSize);
  243. WRITE_DEBUG('TThread.Create done'#13#10);
  244. end;
  245. procedure TThread.SysDestroy;
  246. begin
  247. if FThreadID = GetCurrentThreadID then begin
  248. raise EThreadDestroyCalled.Create('A thread cannot destroy itself except by setting FreeOnTerminate and leaving!');
  249. end;
  250. // if someone calls .Free on a thread with
  251. // FreeOnTerminate, then don't crash!
  252. FFreeOnTerminate := false;
  253. if not FFinished and not FSuspended then begin
  254. Terminate;
  255. WaitFor;
  256. end;
  257. if (FInitialSuspended) then begin
  258. // thread was created suspended but never woken up.
  259. SemaphorePost(FSem);
  260. WaitFor;
  261. end;
  262. FFatalException.Free;
  263. FFatalException := nil;
  264. SemaphoreDestroy(FSem);
  265. RemoveThread(self); {remove it from the list of active threads}
  266. end;
  267. procedure TThread.SetSuspended(Value: Boolean);
  268. begin
  269. if Value <> FSuspended then
  270. if Value then
  271. Suspend
  272. else
  273. Resume;
  274. end;
  275. procedure TThread.Suspend;
  276. begin
  277. if not FSuspended then begin
  278. if FThreadID = GetCurrentThreadID then begin
  279. FSuspended := true;
  280. SemaphoreWait(FSem);
  281. end else begin
  282. FSuspendedExternal := true;
  283. {$IFDEF LINUX}
  284. // naughty hack if the user doesn't have Linux with NPTL...
  285. // in that case, the PID of threads will not be identical
  286. // to the other threads, which means that our thread is a normal
  287. // process that we can suspend via SIGSTOP...
  288. // this violates POSIX, but is the way it works on the
  289. // LinuxThreads pthread implementation. Not with NPTL, but in that case
  290. // getpid(2) also behaves properly and returns the same PID for
  291. // all threads. Thats actually (FINALLY!) native thread support :-)
  292. if FPid <> GMainPID then begin
  293. FSuspended := true;
  294. fpkill(FPid, SIGSTOP);
  295. end;
  296. {$ELSE}
  297. SuspendThread(FHandle);
  298. {$ENDIF}
  299. end;
  300. end;
  301. end;
  302. procedure TThread.Resume;
  303. begin
  304. if (not FSuspendedExternal) then begin
  305. if FSuspended then begin
  306. SemaphorePost(FSem);
  307. FInitialSuspended := false;
  308. FSuspended := False;
  309. end;
  310. end else begin
  311. {$IFDEF LINUX}
  312. // see .Suspend
  313. if FPid <> GMainPID then begin
  314. fpkill(FPid, SIGCONT);
  315. FSuspended := False;
  316. end;
  317. {$ELSE}
  318. ResumeThread(FHandle);
  319. {$ENDIF}
  320. FSuspendedExternal := false;
  321. end;
  322. end;
  323. procedure TThread.Terminate;
  324. begin
  325. FTerminated := True;
  326. TerminatedSet;
  327. end;
  328. function TThread.WaitFor: Integer;
  329. begin
  330. WRITE_DEBUG('waiting for thread ',FHandle);
  331. WaitFor := WaitForThreadTerminate(FHandle, 0);
  332. WRITE_DEBUG('thread terminated');
  333. end;
  334. procedure TThread.CallOnTerminate;
  335. begin
  336. // no need to check if FOnTerminate <> nil, because
  337. // thats already done in DoTerminate
  338. FOnTerminate(self);
  339. end;
  340. procedure TThread.DoTerminate;
  341. begin
  342. if Assigned(FOnTerminate) then
  343. Synchronize(@CallOnTerminate);
  344. end;
  345. function TThread.GetPriority: TThreadPriority;
  346. var
  347. P: Integer;
  348. I: TThreadPriority;
  349. begin
  350. P := ThreadGetPriority(FHandle);
  351. Result := tpNormal;
  352. for I := Low(TThreadPriority) to High(TThreadPriority) do
  353. if Priorities[I] = P then
  354. Result := I;
  355. end;
  356. procedure TThread.SetPriority(Value: TThreadPriority);
  357. begin
  358. ThreadSetPriority(FHandle, Priorities[Value]);
  359. end;