tthread.inc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  1. {
  2. $Id$
  3. This file is part of the Free Pascal run time library.
  4. (c) 2000-2003 by Marco van de Voort
  5. member of the Free Pascal development team.
  6. See the file COPYING.FPC, included in this distribution,
  7. for details about the copyright.
  8. TThread implementation old (1.0) and new (pthreads) style
  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. {$IFDEF VER1_0} // leaving the old implementation in for now...
  14. type
  15. PThreadRec=^TThreadRec;
  16. TThreadRec=record
  17. thread : TThread;
  18. next : PThreadRec;
  19. end;
  20. var
  21. ThreadRoot : PThreadRec;
  22. ThreadsInited : boolean;
  23. // MainThreadID: longint;
  24. Const
  25. ThreadCount: longint = 0;
  26. function ThreadSelf:TThread;
  27. var
  28. hp : PThreadRec;
  29. sp : Pointer;
  30. begin
  31. sp:=SPtr;
  32. hp:=ThreadRoot;
  33. while assigned(hp) do
  34. begin
  35. if (sp<=hp^.Thread.FStackPointer) and
  36. (sp>(hp^.Thread.FStackPointer-hp^.Thread.FStackSize)) then
  37. begin
  38. Result:=hp^.Thread;
  39. exit;
  40. end;
  41. hp:=hp^.next;
  42. end;
  43. Result:=nil;
  44. end;
  45. //function SIGCHLDHandler(Sig: longint): longint; cdecl;//this is std linux C declaration as function
  46. procedure SIGCHLDHandler(Sig: longint); cdecl;
  47. begin
  48. fpwaitpid(-1, nil, WNOHANG);
  49. end;
  50. procedure InitThreads;
  51. var
  52. Act, OldAct: Baseunix.PSigActionRec;
  53. begin
  54. ThreadRoot:=nil;
  55. ThreadsInited:=true;
  56. // This will install SIGCHLD signal handler
  57. // signal() installs "one-shot" handler,
  58. // so it is better to install and set up handler with sigaction()
  59. GetMem(Act, SizeOf(SigActionRec));
  60. GetMem(OldAct, SizeOf(SigActionRec));
  61. Act^.sa_handler := TSigAction(@SIGCHLDHandler);
  62. Act^.sa_flags := SA_NOCLDSTOP {or SA_NOMASK or SA_RESTART};
  63. Fillchar(Act^.sa_mask,sizeof(Act^.sa_mask),0); //Do not block all signals ??. Don't need if SA_NOMASK in flags
  64. FpSigAction(SIGCHLD, Act, OldAct);
  65. FreeMem(Act, SizeOf(SigActionRec));
  66. FreeMem(OldAct, SizeOf(SigActionRec));
  67. end;
  68. procedure DoneThreads;
  69. var
  70. hp : PThreadRec;
  71. begin
  72. while assigned(ThreadRoot) do
  73. begin
  74. ThreadRoot^.Thread.Destroy;
  75. hp:=ThreadRoot;
  76. ThreadRoot:=ThreadRoot^.Next;
  77. dispose(hp);
  78. end;
  79. ThreadsInited:=false;
  80. end;
  81. procedure AddThread(t:TThread);
  82. var
  83. hp : PThreadRec;
  84. begin
  85. { Need to initialize threads ? }
  86. if not ThreadsInited then
  87. InitThreads;
  88. { Put thread in the linked list }
  89. new(hp);
  90. hp^.Thread:=t;
  91. hp^.next:=ThreadRoot;
  92. ThreadRoot:=hp;
  93. inc(ThreadCount, 1);
  94. end;
  95. procedure RemoveThread(t:TThread);
  96. var
  97. lasthp,hp : PThreadRec;
  98. begin
  99. hp:=ThreadRoot;
  100. lasthp:=nil;
  101. while assigned(hp) do
  102. begin
  103. if hp^.Thread=t then
  104. begin
  105. if assigned(lasthp) then
  106. lasthp^.next:=hp^.next
  107. else
  108. ThreadRoot:=hp^.next;
  109. dispose(hp);
  110. exit;
  111. end;
  112. lasthp:=hp;
  113. hp:=hp^.next;
  114. end;
  115. Dec(ThreadCount, 1);
  116. if ThreadCount = 0 then DoneThreads;
  117. end;
  118. { TThread }
  119. function ThreadProc(args:pointer): Integer;cdecl;
  120. var
  121. FreeThread: Boolean;
  122. Thread : TThread absolute args;
  123. begin
  124. while Thread.FHandle = 0 do fpsleep(1);
  125. if Thread.FSuspended then Thread.suspend();
  126. try
  127. Thread.Execute;
  128. except
  129. Thread.FFatalException := TObject(AcquireExceptionObject);
  130. end;
  131. FreeThread := Thread.FFreeOnTerminate;
  132. Result := Thread.FReturnValue;
  133. Thread.FFinished := True;
  134. Thread.DoTerminate;
  135. if FreeThread then
  136. Thread.Free;
  137. fpexit(Result);
  138. end;
  139. constructor TThread.Create(CreateSuspended: Boolean);
  140. var
  141. Flags: Integer;
  142. begin
  143. inherited Create;
  144. AddThread(self);
  145. FSuspended := CreateSuspended;
  146. Flags := CLONE_VM + CLONE_FS + CLONE_FILES + CLONE_SIGHAND + SIGCHLD;
  147. { Setup 16k of stack }
  148. FStackSize:=16384;
  149. Getmem(FStackPointer,FStackSize);
  150. inc(FStackPointer,FStackSize);
  151. FCallExitProcess:=false;
  152. { Clone }
  153. FHandle:= Clone(@ThreadProc,FStackPointer,Flags,self);
  154. // if FSuspended then Suspend;
  155. FThreadID := FHandle;
  156. IsMultiThread := TRUE;
  157. FFatalException := nil;
  158. end;
  159. destructor TThread.Destroy;
  160. begin
  161. if not FFinished and not Suspended then
  162. begin
  163. Terminate;
  164. WaitFor;
  165. end;
  166. if FHandle <> -1 then
  167. fpkill(FHandle, SIGKILL);
  168. dec(FStackPointer,FStackSize);
  169. Freemem(FStackPointer);
  170. FFatalException.Free;
  171. FFatalException := nil;
  172. inherited Destroy;
  173. RemoveThread(self);
  174. end;
  175. procedure TThread.CallOnTerminate;
  176. begin
  177. FOnTerminate(Self);
  178. end;
  179. procedure TThread.DoTerminate;
  180. begin
  181. if Assigned(FOnTerminate) then
  182. Synchronize(@CallOnTerminate);
  183. end;
  184. const
  185. { I Don't know idle or timecritical, value is also 20, so the largest other
  186. possibility is 19 (PFV) }
  187. Priorities: array [TThreadPriority] of Integer =
  188. (-20,-19,-10,9,10,19,20);
  189. function TThread.GetPriority: TThreadPriority;
  190. var
  191. P: Integer;
  192. I: TThreadPriority;
  193. begin
  194. P := fpGetPriority(Prio_Process,FHandle);
  195. Result := tpNormal;
  196. for I := Low(TThreadPriority) to High(TThreadPriority) do
  197. if Priorities[I] = P then
  198. Result := I;
  199. end;
  200. procedure TThread.SetPriority(Value: TThreadPriority);
  201. begin
  202. fpSetPriority(Prio_Process,FHandle,Priorities[Value]);
  203. end;
  204. procedure TThread.Synchronize(Method: TThreadMethod);
  205. begin
  206. FSynchronizeException := nil;
  207. FMethod := Method;
  208. { SendMessage(ThreadWindow, CM_EXECPROC, 0, Longint(Self)); }
  209. if Assigned(FSynchronizeException) then
  210. raise FSynchronizeException;
  211. end;
  212. procedure TThread.SetSuspended(Value: Boolean);
  213. begin
  214. if Value <> FSuspended then
  215. if Value then
  216. Suspend
  217. else
  218. Resume;
  219. end;
  220. procedure TThread.Suspend;
  221. begin
  222. FSuspended := true;
  223. fpKill(FHandle, SIGSTOP);
  224. end;
  225. procedure TThread.Resume;
  226. begin
  227. fpKill(FHandle, SIGCONT);
  228. FSuspended := False;
  229. end;
  230. procedure TThread.Terminate;
  231. begin
  232. FTerminated := True;
  233. end;
  234. function TThread.WaitFor: Integer;
  235. var
  236. status : longint;
  237. begin
  238. if FThreadID = MainThreadID then
  239. fpwaitpid(0,@status,0)
  240. else
  241. fpwaitpid(FHandle,@status,0);
  242. Result:=status;
  243. end;
  244. {$ELSE}
  245. {
  246. What follows, is a short description on my implementation of TThread.
  247. Most information can also be found by reading the source and accompanying
  248. comments.
  249. A thread is created using BeginThread, which in turn calls
  250. pthread_create. So the threads here are always posix threads.
  251. Posix doesn't define anything for suspending threads as this is
  252. inherintly unsafe. Just don't suspend threads at points they cannot
  253. control. Therefore, I didn't implement .Suspend() if its called from
  254. outside the threads execution flow (except on Linux _without_ NPTL).
  255. The implementation for .suspend uses a semaphore, which is initialized
  256. at thread creation. If the thread tries to suspend itself, we simply
  257. let it wait on the semaphore until it is unblocked by someone else
  258. who calls .Resume.
  259. If a thread is supposed to be suspended (from outside its own path of
  260. execution) on a system where the symbol LINUX is defined, two things
  261. are possible.
  262. 1) the system has the LinuxThreads pthread implementation
  263. 2) the system has NPTL as the pthread implementation.
  264. In the first case, each thread is a process on its own, which as far as
  265. know actually violates posix with respect to signal handling.
  266. But we can detect this case, because getpid(2) will
  267. return a different PID for each thread. In that case, sending SIGSTOP
  268. to the PID associated with a thread will actually stop that thread
  269. only.
  270. In the second case, this is not possible. But getpid(2) returns the same
  271. PID across all threads, which is detected, and TThread.Suspend() does
  272. nothing in that case. This should probably be changed, but I know of
  273. no way to suspend a thread when using NPTL.
  274. If the symbol LINUX is not defined, then the unimplemented
  275. function SuspendThread is called.
  276. Johannes Berg <[email protected]>, Sunday, November 16 2003
  277. }
  278. // ========== semaphore stuff ==========
  279. {
  280. I don't like this. It eats up 2 filedescriptors for each thread,
  281. and those are a limited resource. If you have a server programm
  282. handling client connections (one per thread) it will not be able
  283. to handle many if we use 2 fds already for internal structures.
  284. However, right now I don't see a better option unless some sem_*
  285. functions are added to systhrds.
  286. I encapsulated all used functions here to make it easier to
  287. change them completely.
  288. }
  289. function SemaphoreInit: Pointer;
  290. begin
  291. SemaphoreInit := GetMem(SizeOf(TFilDes));
  292. fppipe(PFilDes(SemaphoreInit)^);
  293. end;
  294. procedure SemaphoreWait(const FSem: Pointer);
  295. var
  296. b: byte;
  297. begin
  298. fpread(PFilDes(FSem)^[0], b, 1);
  299. end;
  300. procedure SemaphorePost(const FSem: Pointer);
  301. begin
  302. fpwrite(PFilDes(FSem)^[1], #0, 1);
  303. end;
  304. procedure SemaphoreDestroy(const FSem: Pointer);
  305. begin
  306. fpclose(PFilDes(FSem)^[0]);
  307. fpclose(PFilDes(FSem)^[1]);
  308. FreeMemory(FSem);
  309. end;
  310. // =========== semaphore end ===========
  311. var
  312. ThreadsInited: boolean = false;
  313. {$IFDEF LINUX}
  314. GMainPID: LongInt = 0;
  315. {$ENDIF}
  316. const
  317. // stupid, considering its not even implemented...
  318. Priorities: array [TThreadPriority] of Integer =
  319. (-20,-19,-10,0,9,18,19);
  320. procedure InitThreads;
  321. begin
  322. if not ThreadsInited then begin
  323. ThreadsInited := true;
  324. {$IFDEF LINUX}
  325. GMainPid := fpgetpid();
  326. {$ENDIF}
  327. end;
  328. end;
  329. procedure DoneThreads;
  330. begin
  331. ThreadsInited := false;
  332. end;
  333. { ok, so this is a hack, but it works nicely. Just never use
  334. a multiline argument with WRITE_DEBUG! }
  335. {$MACRO ON}
  336. {$IFDEF DEBUG_MT}
  337. {$define WRITE_DEBUG := writeln} // actually write something
  338. {$ELSE}
  339. {$define WRITE_DEBUG := //} // just comment out those lines
  340. {$ENDIF}
  341. function ThreadFunc(parameter: Pointer): LongInt; cdecl;
  342. var
  343. LThread: TThread;
  344. c: char;
  345. begin
  346. WRITE_DEBUG('ThreadFunc is here...');
  347. LThread := TThread(parameter);
  348. {$IFDEF LINUX}
  349. // save the PID of the "thread"
  350. // this is different from the PID of the main thread if
  351. // the LinuxThreads implementation is used
  352. LThread.FPid := fpgetpid();
  353. {$ENDIF}
  354. WRITE_DEBUG('thread initing, parameter = ', LongInt(LThread));
  355. try
  356. if LThread.FInitialSuspended then begin
  357. SemaphoreWait(LThread.FSem);
  358. if not LThread.FInitialSuspended then begin
  359. WRITE_DEBUG('going into LThread.Execute');
  360. LThread.Execute;
  361. end;
  362. end else begin
  363. WRITE_DEBUG('going into LThread.Execute');
  364. LThread.Execute;
  365. end;
  366. except
  367. on e: exception do begin
  368. WRITE_DEBUG('got exception: ',e.message);
  369. LThread.FFatalException := TObject(AcquireExceptionObject);
  370. // not sure if we should really do this...
  371. // but .Destroy was called, so why not try FreeOnTerminate?
  372. if e is EThreadDestroyCalled then LThread.FFreeOnTerminate := true;
  373. end;
  374. end;
  375. WRITE_DEBUG('thread done running');
  376. Result := LThread.FReturnValue;
  377. WRITE_DEBUG('Result is ',Result);
  378. LThread.FFinished := True;
  379. LThread.DoTerminate;
  380. if LThread.FreeOnTerminate then begin
  381. WRITE_DEBUG('Thread should be freed');
  382. LThread.Free;
  383. WRITE_DEBUG('Thread freed');
  384. end;
  385. WRITE_DEBUG('thread func exiting');
  386. end;
  387. { TThread }
  388. constructor TThread.Create(CreateSuspended: Boolean);
  389. begin
  390. // lets just hope that the user doesn't create a thread
  391. // via BeginThread and creates the first TThread Object in there!
  392. InitThreads;
  393. inherited Create;
  394. FSem := SemaphoreInit;
  395. FSuspended := CreateSuspended;
  396. FSuspendedExternal := false;
  397. FInitialSuspended := CreateSuspended;
  398. FFatalException := nil;
  399. WRITE_DEBUG('creating thread, self = ',longint(self));
  400. FHandle:= BeginThread(@ThreadFunc, Pointer(Self), FThreadID);
  401. WRITE_DEBUG('TThread.Create done');
  402. end;
  403. destructor TThread.Destroy;
  404. begin
  405. if FThreadID = GetCurrentThreadID then begin
  406. raise EThreadDestroyCalled.Create('A thread cannot destroy itself except by setting FreeOnTerminate and leaving!');
  407. end;
  408. // if someone calls .Free on a thread with
  409. // FreeOnTerminate, then don't crash!
  410. FFreeOnTerminate := false;
  411. if not FFinished and not FSuspended then begin
  412. Terminate;
  413. WaitFor;
  414. end;
  415. if (FInitialSuspended) then begin
  416. // thread was created suspended but never woken up.
  417. SemaphorePost(FSem);
  418. WaitFor;
  419. end;
  420. FFatalException.Free;
  421. FFatalException := nil;
  422. SemaphoreDestroy(FSem);
  423. inherited Destroy;
  424. end;
  425. procedure TThread.SetSuspended(Value: Boolean);
  426. begin
  427. if Value <> FSuspended then
  428. if Value then
  429. Suspend
  430. else
  431. Resume;
  432. end;
  433. procedure TThread.Suspend;
  434. begin
  435. if not FSuspended then begin
  436. if FThreadID = GetCurrentThreadID then begin
  437. FSuspended := true;
  438. SemaphoreWait(FSem);
  439. end else begin
  440. FSuspendedExternal := true;
  441. {$IFDEF LINUX}
  442. // naughty hack if the user doesn't have Linux with NPTL...
  443. // in that case, the PID of threads will not be identical
  444. // to the other threads, which means that our thread is a normal
  445. // process that we can suspend via SIGSTOP...
  446. // this violates POSIX, but is the way it works on the
  447. // LinuxThreads pthread implementation. Not with NPTL, but in that case
  448. // getpid(2) also behaves properly and returns the same PID for
  449. // all threads. Thats actually (FINALLY!) native thread support :-)
  450. if FPid <> GMainPID then begin
  451. FSuspended := true;
  452. fpkill(FPid, SIGSTOP);
  453. end;
  454. {$ELSE}
  455. SuspendThread(FHandle);
  456. {$ENDIF}
  457. end;
  458. end;
  459. end;
  460. procedure TThread.Resume;
  461. begin
  462. if (not FSuspendedExternal) then begin
  463. if FSuspended then begin
  464. SemaphorePost(FSem);
  465. FInitialSuspended := false;
  466. FSuspended := False;
  467. end;
  468. end else begin
  469. {$IFDEF LINUX}
  470. // see .Suspend
  471. if FPid <> GMainPID then begin
  472. fpkill(FPid, SIGCONT);
  473. FSuspended := False;
  474. end;
  475. {$ELSE}
  476. ResumeThread(FHandle);
  477. {$ENDIF}
  478. FSuspendedExternal := false;
  479. end;
  480. end;
  481. procedure TThread.Terminate;
  482. begin
  483. FTerminated := True;
  484. end;
  485. function TThread.WaitFor: Integer;
  486. begin
  487. WRITE_DEBUG('waiting for thread ',FHandle);
  488. WaitFor := WaitForThreadTerminate(FHandle, 0);
  489. WRITE_DEBUG('thread terminated');
  490. end;
  491. procedure TThread.CallOnTerminate;
  492. begin
  493. // no need to check if FOnTerminate <> nil, because
  494. // thats already done in DoTerminate
  495. FOnTerminate(self);
  496. end;
  497. procedure TThread.DoTerminate;
  498. begin
  499. if Assigned(FOnTerminate) then
  500. Synchronize(@CallOnTerminate);
  501. end;
  502. function TThread.GetPriority: TThreadPriority;
  503. var
  504. P: Integer;
  505. I: TThreadPriority;
  506. begin
  507. P := ThreadGetPriority(FHandle);
  508. Result := tpNormal;
  509. for I := Low(TThreadPriority) to High(TThreadPriority) do
  510. if Priorities[I] = P then
  511. Result := I;
  512. end;
  513. procedure TThread.Synchronize(Method: TThreadMethod);
  514. begin
  515. {$TODO someone with more clue of the GUI stuff will have to do this}
  516. end;
  517. procedure TThread.SetPriority(Value: TThreadPriority);
  518. begin
  519. ThreadSetPriority(FHandle, Priorities[Value]);
  520. end;
  521. {$ENDIF}
  522. {
  523. $Log$
  524. Revision 1.2 2004-01-04 01:11:28 marco
  525. * a new qod port of the freebsd rtl. To be refined in the coming days.
  526. Revision 1.8 2004/01/03 12:18:29 marco
  527. * a lot of copyright notices and CVS logs added and fixed
  528. Revision 1.7 2003/11/22 11:04:08 marco
  529. * Johill: suspend fix
  530. Revision 1.6 2003/11/19 10:12:02 marco
  531. * more cleanups
  532. Revision 1.5 2003/11/17 10:05:51 marco
  533. * threads for FreeBSD. Not working tho
  534. Revision 1.4 2003/11/17 08:27:49 marco
  535. * pthreads based ttread from Johannes Berg
  536. Revision 1.3 2003/11/10 16:54:28 marco
  537. * new oldlinux unit. 1_0 defines killed in some former FCL parts.
  538. Revision 1.2 2003/11/03 09:42:28 marco
  539. * Peter's Cardinal<->Longint fixes patch
  540. Revision 1.1 2003/10/06 21:01:06 peter
  541. * moved classes unit to rtl
  542. Revision 1.9 2003/10/06 17:06:55 florian
  543. * applied Johannes Berg's patch for exception handling in threads
  544. Revision 1.8 2003/09/20 15:10:30 marco
  545. * small fixes. fcl now compiles
  546. Revision 1.7 2002/12/18 20:44:36 peter
  547. * use fillchar to clear sigset
  548. Revision 1.6 2002/09/07 15:15:27 peter
  549. * old logs removed and tabs fixed
  550. }