tthread.inc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  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.SetSuspended(Value: Boolean);
  205. begin
  206. if Value <> FSuspended then
  207. if Value then
  208. Suspend
  209. else
  210. Resume;
  211. end;
  212. procedure TThread.Suspend;
  213. begin
  214. FSuspended := true;
  215. fpKill(FHandle, SIGSTOP);
  216. end;
  217. procedure TThread.Resume;
  218. begin
  219. fpKill(FHandle, SIGCONT);
  220. FSuspended := False;
  221. end;
  222. procedure TThread.Terminate;
  223. begin
  224. FTerminated := True;
  225. end;
  226. function TThread.WaitFor: Integer;
  227. var
  228. status : longint;
  229. begin
  230. if FThreadID = MainThreadID then
  231. fpwaitpid(0,@status,0)
  232. else
  233. fpwaitpid(FHandle,@status,0);
  234. Result:=status;
  235. end;
  236. {$ELSE}
  237. {
  238. What follows, is a short description on my implementation of TThread.
  239. Most information can also be found by reading the source and accompanying
  240. comments.
  241. A thread is created using BeginThread, which in turn calls
  242. pthread_create. So the threads here are always posix threads.
  243. Posix doesn't define anything for suspending threads as this is
  244. inherintly unsafe. Just don't suspend threads at points they cannot
  245. control. Therefore, I didn't implement .Suspend() if its called from
  246. outside the threads execution flow (except on Linux _without_ NPTL).
  247. The implementation for .suspend uses a semaphore, which is initialized
  248. at thread creation. If the thread tries to suspend itself, we simply
  249. let it wait on the semaphore until it is unblocked by someone else
  250. who calls .Resume.
  251. If a thread is supposed to be suspended (from outside its own path of
  252. execution) on a system where the symbol LINUX is defined, two things
  253. are possible.
  254. 1) the system has the LinuxThreads pthread implementation
  255. 2) the system has NPTL as the pthread implementation.
  256. In the first case, each thread is a process on its own, which as far as
  257. know actually violates posix with respect to signal handling.
  258. But we can detect this case, because getpid(2) will
  259. return a different PID for each thread. In that case, sending SIGSTOP
  260. to the PID associated with a thread will actually stop that thread
  261. only.
  262. In the second case, this is not possible. But getpid(2) returns the same
  263. PID across all threads, which is detected, and TThread.Suspend() does
  264. nothing in that case. This should probably be changed, but I know of
  265. no way to suspend a thread when using NPTL.
  266. If the symbol LINUX is not defined, then the unimplemented
  267. function SuspendThread is called.
  268. Johannes Berg <[email protected]>, Sunday, November 16 2003
  269. }
  270. // ========== semaphore stuff ==========
  271. {
  272. I don't like this. It eats up 2 filedescriptors for each thread,
  273. and those are a limited resource. If you have a server programm
  274. handling client connections (one per thread) it will not be able
  275. to handle many if we use 2 fds already for internal structures.
  276. However, right now I don't see a better option unless some sem_*
  277. functions are added to systhrds.
  278. I encapsulated all used functions here to make it easier to
  279. change them completely.
  280. }
  281. function SemaphoreInit: Pointer;
  282. begin
  283. SemaphoreInit := GetMem(SizeOf(TFilDes));
  284. fppipe(PFilDes(SemaphoreInit)^);
  285. end;
  286. procedure SemaphoreWait(const FSem: Pointer);
  287. var
  288. b: byte;
  289. begin
  290. fpread(PFilDes(FSem)^[0], b, 1);
  291. end;
  292. procedure SemaphorePost(const FSem: Pointer);
  293. begin
  294. fpwrite(PFilDes(FSem)^[1], #0, 1);
  295. end;
  296. procedure SemaphoreDestroy(const FSem: Pointer);
  297. begin
  298. fpclose(PFilDes(FSem)^[0]);
  299. fpclose(PFilDes(FSem)^[1]);
  300. FreeMemory(FSem);
  301. end;
  302. // =========== semaphore end ===========
  303. var
  304. ThreadsInited: boolean = false;
  305. {$IFDEF LINUX}
  306. GMainPID: LongInt = 0;
  307. {$ENDIF}
  308. const
  309. // stupid, considering its not even implemented...
  310. Priorities: array [TThreadPriority] of Integer =
  311. (-20,-19,-10,0,9,18,19);
  312. procedure InitThreads;
  313. begin
  314. if not ThreadsInited then begin
  315. ThreadsInited := true;
  316. {$IFDEF LINUX}
  317. GMainPid := fpgetpid();
  318. {$ENDIF}
  319. end;
  320. end;
  321. procedure DoneThreads;
  322. begin
  323. ThreadsInited := false;
  324. end;
  325. { ok, so this is a hack, but it works nicely. Just never use
  326. a multiline argument with WRITE_DEBUG! }
  327. {$MACRO ON}
  328. {$IFDEF DEBUG_MT}
  329. {$define WRITE_DEBUG := writeln} // actually write something
  330. {$ELSE}
  331. {$define WRITE_DEBUG := //} // just comment out those lines
  332. {$ENDIF}
  333. function ThreadFunc(parameter: Pointer): LongInt; cdecl;
  334. var
  335. LThread: TThread;
  336. c: char;
  337. begin
  338. WRITE_DEBUG('ThreadFunc is here...');
  339. LThread := TThread(parameter);
  340. {$IFDEF LINUX}
  341. // save the PID of the "thread"
  342. // this is different from the PID of the main thread if
  343. // the LinuxThreads implementation is used
  344. LThread.FPid := fpgetpid();
  345. {$ENDIF}
  346. WRITE_DEBUG('thread initing, parameter = ', LongInt(LThread));
  347. try
  348. if LThread.FInitialSuspended then begin
  349. SemaphoreWait(LThread.FSem);
  350. if not LThread.FInitialSuspended then begin
  351. WRITE_DEBUG('going into LThread.Execute');
  352. LThread.Execute;
  353. end;
  354. end else begin
  355. WRITE_DEBUG('going into LThread.Execute');
  356. LThread.Execute;
  357. end;
  358. except
  359. on e: exception do begin
  360. WRITE_DEBUG('got exception: ',e.message);
  361. LThread.FFatalException := TObject(AcquireExceptionObject);
  362. // not sure if we should really do this...
  363. // but .Destroy was called, so why not try FreeOnTerminate?
  364. if e is EThreadDestroyCalled then LThread.FFreeOnTerminate := true;
  365. end;
  366. end;
  367. WRITE_DEBUG('thread done running');
  368. Result := LThread.FReturnValue;
  369. WRITE_DEBUG('Result is ',Result);
  370. LThread.FFinished := True;
  371. LThread.DoTerminate;
  372. if LThread.FreeOnTerminate then begin
  373. WRITE_DEBUG('Thread should be freed');
  374. LThread.Free;
  375. WRITE_DEBUG('Thread freed');
  376. end;
  377. WRITE_DEBUG('thread func exiting');
  378. end;
  379. { TThread }
  380. constructor TThread.Create(CreateSuspended: Boolean);
  381. begin
  382. // lets just hope that the user doesn't create a thread
  383. // via BeginThread and creates the first TThread Object in there!
  384. InitThreads;
  385. inherited Create;
  386. FSem := SemaphoreInit;
  387. FSuspended := CreateSuspended;
  388. FSuspendedExternal := false;
  389. FInitialSuspended := CreateSuspended;
  390. FFatalException := nil;
  391. WRITE_DEBUG('creating thread, self = ',longint(self));
  392. FHandle:= BeginThread(@ThreadFunc, Pointer(Self), FThreadID);
  393. WRITE_DEBUG('TThread.Create done');
  394. end;
  395. destructor TThread.Destroy;
  396. begin
  397. if FThreadID = GetCurrentThreadID then begin
  398. raise EThreadDestroyCalled.Create('A thread cannot destroy itself except by setting FreeOnTerminate and leaving!');
  399. end;
  400. // if someone calls .Free on a thread with
  401. // FreeOnTerminate, then don't crash!
  402. FFreeOnTerminate := false;
  403. if not FFinished and not FSuspended then begin
  404. Terminate;
  405. WaitFor;
  406. end;
  407. if (FInitialSuspended) then begin
  408. // thread was created suspended but never woken up.
  409. SemaphorePost(FSem);
  410. WaitFor;
  411. end;
  412. FFatalException.Free;
  413. FFatalException := nil;
  414. SemaphoreDestroy(FSem);
  415. inherited Destroy;
  416. end;
  417. procedure TThread.SetSuspended(Value: Boolean);
  418. begin
  419. if Value <> FSuspended then
  420. if Value then
  421. Suspend
  422. else
  423. Resume;
  424. end;
  425. procedure TThread.Suspend;
  426. begin
  427. if not FSuspended then begin
  428. if FThreadID = GetCurrentThreadID then begin
  429. FSuspended := true;
  430. SemaphoreWait(FSem);
  431. end else begin
  432. FSuspendedExternal := true;
  433. {$IFDEF LINUX}
  434. // naughty hack if the user doesn't have Linux with NPTL...
  435. // in that case, the PID of threads will not be identical
  436. // to the other threads, which means that our thread is a normal
  437. // process that we can suspend via SIGSTOP...
  438. // this violates POSIX, but is the way it works on the
  439. // LinuxThreads pthread implementation. Not with NPTL, but in that case
  440. // getpid(2) also behaves properly and returns the same PID for
  441. // all threads. Thats actually (FINALLY!) native thread support :-)
  442. if FPid <> GMainPID then begin
  443. FSuspended := true;
  444. fpkill(FPid, SIGSTOP);
  445. end;
  446. {$ELSE}
  447. SuspendThread(FHandle);
  448. {$ENDIF}
  449. end;
  450. end;
  451. end;
  452. procedure TThread.Resume;
  453. begin
  454. if (not FSuspendedExternal) then begin
  455. if FSuspended then begin
  456. SemaphorePost(FSem);
  457. FInitialSuspended := false;
  458. FSuspended := False;
  459. end;
  460. end else begin
  461. {$IFDEF LINUX}
  462. // see .Suspend
  463. if FPid <> GMainPID then begin
  464. fpkill(FPid, SIGCONT);
  465. FSuspended := False;
  466. end;
  467. {$ELSE}
  468. ResumeThread(FHandle);
  469. {$ENDIF}
  470. FSuspendedExternal := false;
  471. end;
  472. end;
  473. procedure TThread.Terminate;
  474. begin
  475. FTerminated := True;
  476. end;
  477. function TThread.WaitFor: Integer;
  478. begin
  479. WRITE_DEBUG('waiting for thread ',FHandle);
  480. WaitFor := WaitForThreadTerminate(FHandle, 0);
  481. WRITE_DEBUG('thread terminated');
  482. end;
  483. procedure TThread.CallOnTerminate;
  484. begin
  485. // no need to check if FOnTerminate <> nil, because
  486. // thats already done in DoTerminate
  487. FOnTerminate(self);
  488. end;
  489. procedure TThread.DoTerminate;
  490. begin
  491. if Assigned(FOnTerminate) then
  492. Synchronize(@CallOnTerminate);
  493. end;
  494. function TThread.GetPriority: TThreadPriority;
  495. var
  496. P: Integer;
  497. I: TThreadPriority;
  498. begin
  499. P := ThreadGetPriority(FHandle);
  500. Result := tpNormal;
  501. for I := Low(TThreadPriority) to High(TThreadPriority) do
  502. if Priorities[I] = P then
  503. Result := I;
  504. end;
  505. procedure TThread.SetPriority(Value: TThreadPriority);
  506. begin
  507. ThreadSetPriority(FHandle, Priorities[Value]);
  508. end;
  509. {$ENDIF}
  510. {
  511. $Log$
  512. Revision 1.4 2005-02-25 21:41:09 florian
  513. * generic tthread.synchronize
  514. * delphi compatible wakemainthread
  515. Revision 1.3 2005/02/14 17:13:30 peter
  516. * truncate log
  517. }