tthread.inc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. {
  2. This file is part of the Free Component Library (FCL)
  3. Copyright (c) 1999-2000 by Peter Vreman
  4. BeOS 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. {$IFDEF VER1_0} // leaving the old implementation in for now...
  12. type
  13. PThreadRec=^TThreadRec;
  14. TThreadRec=record
  15. thread : TThread;
  16. next : PThreadRec;
  17. end;
  18. var
  19. ThreadRoot : PThreadRec;
  20. ThreadsInited : boolean;
  21. // MainThreadID: longint;
  22. Const
  23. ThreadCount: longint = 0;
  24. function ThreadSelf:TThread;
  25. var
  26. hp : PThreadRec;
  27. sp : Pointer;
  28. begin
  29. sp:=SPtr;
  30. hp:=ThreadRoot;
  31. while assigned(hp) do
  32. begin
  33. if (sp<=hp^.Thread.FStackPointer) and
  34. (sp>(hp^.Thread.FStackPointer-hp^.Thread.FStackSize)) then
  35. begin
  36. Result:=hp^.Thread;
  37. exit;
  38. end;
  39. hp:=hp^.next;
  40. end;
  41. Result:=nil;
  42. end;
  43. //function SIGCHLDHandler(Sig: longint): longint; cdecl;//this is std linux C declaration as function
  44. procedure SIGCHLDHandler(Sig: longint); cdecl;
  45. begin
  46. fpwaitpid(-1, nil, WNOHANG);
  47. end;
  48. procedure InitThreads;
  49. var
  50. Act, OldAct: Baseunix.PSigActionRec;
  51. begin
  52. ThreadRoot:=nil;
  53. ThreadsInited:=true;
  54. // This will install SIGCHLD signal handler
  55. // signal() installs "one-shot" handler,
  56. // so it is better to install and set up handler with sigaction()
  57. GetMem(Act, SizeOf(SigActionRec));
  58. GetMem(OldAct, SizeOf(SigActionRec));
  59. Act^.sa_handler := TSigAction(@SIGCHLDHandler);
  60. Act^.sa_flags := SA_NOCLDSTOP {or SA_NOMASK or SA_RESTART};
  61. Fillchar(Act^.sa_mask,sizeof(Act^.sa_mask),0); //Do not block all signals ??. Don't need if SA_NOMASK in flags
  62. FpSigAction(SIGCHLD, Act, OldAct);
  63. FreeMem(Act, SizeOf(SigActionRec));
  64. FreeMem(OldAct, SizeOf(SigActionRec));
  65. end;
  66. procedure DoneThreads;
  67. var
  68. hp : PThreadRec;
  69. begin
  70. while assigned(ThreadRoot) do
  71. begin
  72. ThreadRoot^.Thread.Destroy;
  73. hp:=ThreadRoot;
  74. ThreadRoot:=ThreadRoot^.Next;
  75. dispose(hp);
  76. end;
  77. ThreadsInited:=false;
  78. end;
  79. procedure AddThread(t:TThread);
  80. var
  81. hp : PThreadRec;
  82. begin
  83. { Need to initialize threads ? }
  84. if not ThreadsInited then
  85. InitThreads;
  86. { Put thread in the linked list }
  87. new(hp);
  88. hp^.Thread:=t;
  89. hp^.next:=ThreadRoot;
  90. ThreadRoot:=hp;
  91. inc(ThreadCount, 1);
  92. end;
  93. procedure RemoveThread(t:TThread);
  94. var
  95. lasthp,hp : PThreadRec;
  96. begin
  97. hp:=ThreadRoot;
  98. lasthp:=nil;
  99. while assigned(hp) do
  100. begin
  101. if hp^.Thread=t then
  102. begin
  103. if assigned(lasthp) then
  104. lasthp^.next:=hp^.next
  105. else
  106. ThreadRoot:=hp^.next;
  107. dispose(hp);
  108. exit;
  109. end;
  110. lasthp:=hp;
  111. hp:=hp^.next;
  112. end;
  113. Dec(ThreadCount, 1);
  114. if ThreadCount = 0 then DoneThreads;
  115. end;
  116. { TThread }
  117. function ThreadProc(args:pointer): Integer;//cdecl;
  118. var
  119. FreeThread: Boolean;
  120. Thread : TThread absolute args;
  121. begin
  122. while Thread.FHandle = 0 do fpsleep(1);
  123. if Thread.FSuspended then Thread.suspend();
  124. try
  125. CurrentThreadVar := Thread;
  126. Thread.Execute;
  127. except
  128. Thread.FFatalException := TObject(AcquireExceptionObject);
  129. end;
  130. FreeThread := Thread.FFreeOnTerminate;
  131. Result := Thread.FReturnValue;
  132. Thread.FFinished := True;
  133. Thread.DoTerminate;
  134. if FreeThread then
  135. Thread.Free;
  136. fpexit(Result);
  137. end;
  138. procedure TThread.SysCreate(CreateSuspended: Boolean;
  139. const StackSize: SizeUInt);
  140. var
  141. Flags: Integer;
  142. begin
  143. AddThread(self);
  144. FSuspended := CreateSuspended;
  145. Flags := CLONE_VM + CLONE_FS + CLONE_FILES + CLONE_SIGHAND + SIGCHLD;
  146. { Setup 16k of stack }
  147. FStackSize:=16384;
  148. Getmem(FStackPointer,StackSize);
  149. inc(FStackPointer,StackSize);
  150. FCallExitProcess:=false;
  151. { Clone }
  152. FHandle:= Clone(@ThreadProc,FStackPointer,Flags,self);
  153. // if FSuspended then Suspend;
  154. FThreadID := FHandle;
  155. IsMultiThread := TRUE;
  156. FFatalException := nil;
  157. end;
  158. procedure TThread.SysDestroy;
  159. begin
  160. if not FFinished and not Suspended then
  161. begin
  162. Terminate;
  163. WaitFor;
  164. end;
  165. if FHandle <> -1 then
  166. fpkill(FHandle, SIGKILL);
  167. dec(FStackPointer,FStackSize);
  168. Freemem(FStackPointer);
  169. FFatalException.Free;
  170. FFatalException := nil;
  171. RemoveThread(self);
  172. end;
  173. procedure TThread.CallOnTerminate;
  174. begin
  175. FOnTerminate(Self);
  176. end;
  177. procedure TThread.DoTerminate;
  178. begin
  179. if Assigned(FOnTerminate) then
  180. Synchronize(@CallOnTerminate);
  181. end;
  182. const
  183. { I Don't know idle or timecritical, value is also 20, so the largest other
  184. possibility is 19 (PFV) }
  185. Priorities: array [TThreadPriority] of Integer =
  186. (-20,-19,-10,9,10,19,20);
  187. function TThread.GetPriority: TThreadPriority;
  188. var
  189. P: Integer;
  190. I: TThreadPriority;
  191. begin
  192. P := fpGetPriority(Prio_Process,FHandle);
  193. Result := tpNormal;
  194. for I := Low(TThreadPriority) to High(TThreadPriority) do
  195. if Priorities[I] = P then
  196. Result := I;
  197. end;
  198. procedure TThread.SetPriority(Value: TThreadPriority);
  199. begin
  200. fpSetPriority(Prio_Process,FHandle,Priorities[Value]);
  201. end;
  202. procedure TThread.Synchronize(Method: TThreadMethod);
  203. begin
  204. end;
  205. procedure TThread.SetSuspended(Value: Boolean);
  206. begin
  207. if Value <> FSuspended then
  208. if Value then
  209. Suspend
  210. else
  211. Resume;
  212. end;
  213. procedure TThread.Suspend;
  214. begin
  215. FSuspended := true;
  216. fpKill(FHandle, SIGSTOP);
  217. end;
  218. procedure TThread.Resume;
  219. begin
  220. fpKill(FHandle, SIGCONT);
  221. FSuspended := False;
  222. end;
  223. procedure TThread.Terminate;
  224. begin
  225. FTerminated := True;
  226. TerminatedSet;
  227. end;
  228. function TThread.WaitFor: Integer;
  229. var
  230. status : longint;
  231. begin
  232. if FThreadID = MainThreadID then
  233. fpwaitpid(0,@status,0)
  234. else
  235. fpwaitpid(FHandle,@status,0);
  236. Result:=status;
  237. end;
  238. {$ELSE}
  239. {
  240. What follows, is a short description on my implementation of TThread.
  241. Most information can also be found by reading the source and accompanying
  242. comments.
  243. A thread is created using BeginThread, which in turn calls
  244. pthread_create. So the threads here are always posix threads.
  245. Posix doesn't define anything for suspending threads as this is
  246. inherintly unsafe. Just don't suspend threads at points they cannot
  247. control. Therefore, I didn't implement .Suspend() if its called from
  248. outside the threads execution flow (except on Linux _without_ NPTL).
  249. The implementation for .suspend uses a semaphore, which is initialized
  250. at thread creation. If the thread tries to suspend itself, we simply
  251. let it wait on the semaphore until it is unblocked by someone else
  252. who calls .Resume.
  253. If a thread is supposed to be suspended (from outside its own path of
  254. execution) on a system where the symbol LINUX is defined, two things
  255. are possible.
  256. 1) the system has the LinuxThreads pthread implementation
  257. 2) the system has NPTL as the pthread implementation.
  258. In the first case, each thread is a process on its own, which as far as
  259. know actually violates posix with respect to signal handling.
  260. But we can detect this case, because getpid(2) will
  261. return a different PID for each thread. In that case, sending SIGSTOP
  262. to the PID associated with a thread will actually stop that thread
  263. only.
  264. In the second case, this is not possible. But getpid(2) returns the same
  265. PID across all threads, which is detected, and TThread.Suspend() does
  266. nothing in that case. This should probably be changed, but I know of
  267. no way to suspend a thread when using NPTL.
  268. If the symbol LINUX is not defined, then the unimplemented
  269. function SuspendThread is called.
  270. Johannes Berg <[email protected]>, Sunday, November 16 2003
  271. }
  272. // ========== semaphore stuff ==========
  273. {
  274. I don't like this. It eats up 2 filedescriptors for each thread,
  275. and those are a limited resource. If you have a server programm
  276. handling client connections (one per thread) it will not be able
  277. to handle many if we use 2 fds already for internal structures.
  278. However, right now I don't see a better option unless some sem_*
  279. functions are added to systhrds.
  280. I encapsulated all used functions here to make it easier to
  281. change them completely.
  282. }
  283. {BeOS implementation}
  284. function SemaphoreInit: Pointer;
  285. begin
  286. SemaphoreInit := GetMem(SizeOf(TFilDes));
  287. fppipe(PFilDes(SemaphoreInit)^);
  288. end;
  289. procedure SemaphoreWait(const FSem: Pointer);
  290. var
  291. b: byte;
  292. begin
  293. fpread(PFilDes(FSem)^[0], b, 1);
  294. end;
  295. procedure SemaphorePost(const FSem: Pointer);
  296. var
  297. b : byte;
  298. begin
  299. b := 0;
  300. fpwrite(PFilDes(FSem)^[1], b, 1);
  301. end;
  302. procedure SemaphoreDestroy(const FSem: Pointer);
  303. begin
  304. fpclose(PFilDes(FSem)^[0]);
  305. fpclose(PFilDes(FSem)^[1]);
  306. FreeMemory(FSem);
  307. end;
  308. // =========== semaphore end ===========
  309. var
  310. ThreadsInited: boolean = false;
  311. {$IFDEF LINUX}
  312. GMainPID: LongInt = 0;
  313. {$ENDIF}
  314. const
  315. // stupid, considering its not even implemented...
  316. Priorities: array [TThreadPriority] of Integer =
  317. (-20,-19,-10,0,9,18,19);
  318. procedure InitThreads;
  319. begin
  320. if not ThreadsInited then begin
  321. ThreadsInited := true;
  322. {$IFDEF LINUX}
  323. GMainPid := fpgetpid();
  324. {$ENDIF}
  325. end;
  326. end;
  327. procedure DoneThreads;
  328. begin
  329. ThreadsInited := false;
  330. end;
  331. { ok, so this is a hack, but it works nicely. Just never use
  332. a multiline argument with WRITE_DEBUG! }
  333. {$MACRO ON}
  334. {$IFDEF DEBUG_MT}
  335. {$define WRITE_DEBUG := writeln} // actually write something
  336. {$ELSE}
  337. {$define WRITE_DEBUG := //} // just comment out those lines
  338. {$ENDIF}
  339. function ThreadFunc(parameter: Pointer): LongInt; // cdecl;
  340. var
  341. LThread: TThread;
  342. c: char;
  343. begin
  344. WRITE_DEBUG('ThreadFunc is here...');
  345. LThread := TThread(parameter);
  346. {$IFDEF LINUX}
  347. // save the PID of the "thread"
  348. // this is different from the PID of the main thread if
  349. // the LinuxThreads implementation is used
  350. LThread.FPid := fpgetpid();
  351. {$ENDIF}
  352. WRITE_DEBUG('thread initing, parameter = ', LongInt(LThread));
  353. try
  354. if LThread.FInitialSuspended then begin
  355. SemaphoreWait(LThread.FSem);
  356. if not LThread.FInitialSuspended then begin
  357. CurrentThreadVar := LThread;
  358. WRITE_DEBUG('going into LThread.Execute');
  359. LThread.Execute;
  360. end;
  361. end else begin
  362. CurrentThreadVar := LThread;
  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. procedure TThread.SysCreate(CreateSuspended: Boolean; const StackSize: SizeUInt);
  389. var
  390. data : pointer;
  391. begin
  392. // lets just hope that the user doesn't create a thread
  393. // via BeginThread and creates the first TThread Object in there!
  394. InitThreads;
  395. FSem := SemaphoreInit;
  396. FSuspended := CreateSuspended;
  397. FSuspendedExternal := false;
  398. FInitialSuspended := CreateSuspended;
  399. FFatalException := nil;
  400. WRITE_DEBUG('creating thread, self = ',longint(self));
  401. FHandle:= BeginThread(@ThreadFunc, Pointer(Self), FThreadID);
  402. WRITE_DEBUG('TThread.Create done');
  403. end;
  404. procedure TThread.SysDestroy;
  405. begin
  406. if FThreadID = GetCurrentThreadID then begin
  407. raise EThreadDestroyCalled.Create('A thread cannot destroy itself except by setting FreeOnTerminate and leaving!');
  408. end;
  409. // if someone calls .Free on a thread with
  410. // FreeOnTerminate, then don't crash!
  411. FFreeOnTerminate := false;
  412. if not FFinished and not FSuspended then begin
  413. Terminate;
  414. WaitFor;
  415. end;
  416. if (FInitialSuspended) then begin
  417. // thread was created suspended but never woken up.
  418. SemaphorePost(FSem);
  419. WaitFor;
  420. end;
  421. FFatalException.Free;
  422. FFatalException := nil;
  423. SemaphoreDestroy(FSem);
  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. TerminatedSet;
  485. end;
  486. function TThread.WaitFor: Integer;
  487. begin
  488. WRITE_DEBUG('waiting for thread ',FHandle);
  489. WaitFor := WaitForThreadTerminate(FHandle, 0);
  490. WRITE_DEBUG('thread terminated');
  491. end;
  492. procedure TThread.CallOnTerminate;
  493. begin
  494. // no need to check if FOnTerminate <> nil, because
  495. // thats already done in DoTerminate
  496. FOnTerminate(self);
  497. end;
  498. procedure TThread.DoTerminate;
  499. begin
  500. if Assigned(FOnTerminate) then
  501. Synchronize(@CallOnTerminate);
  502. end;
  503. function TThread.GetPriority: TThreadPriority;
  504. var
  505. P: Integer;
  506. I: TThreadPriority;
  507. begin
  508. P := ThreadGetPriority(FHandle);
  509. Result := tpNormal;
  510. for I := Low(TThreadPriority) to High(TThreadPriority) do
  511. if Priorities[I] = P then
  512. Result := I;
  513. end;
  514. (*
  515. procedure TThread.Synchronize(Method: TThreadMethod);
  516. begin
  517. {$TODO someone with more clue of the GUI stuff will have to do this}
  518. end;
  519. *)
  520. procedure TThread.SetPriority(Value: TThreadPriority);
  521. begin
  522. ThreadSetPriority(FHandle, Priorities[Value]);
  523. end;
  524. {$ENDIF}