tthread.inc 11 KB

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