tthread.inc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  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. Thread.Execute;
  126. except
  127. Thread.FFatalException := TObject(AcquireExceptionObject);
  128. end;
  129. FreeThread := Thread.FFreeOnTerminate;
  130. Result := Thread.FReturnValue;
  131. Thread.FFinished := True;
  132. Thread.DoTerminate;
  133. if FreeThread then
  134. Thread.Free;
  135. fpexit(Result);
  136. end;
  137. procedure TThread.SysCreate(CreateSuspended: Boolean;
  138. const StackSize: SizeUInt);
  139. var
  140. Flags: Integer;
  141. begin
  142. AddThread(self);
  143. FSuspended := CreateSuspended;
  144. Flags := CLONE_VM + CLONE_FS + CLONE_FILES + CLONE_SIGHAND + SIGCHLD;
  145. { Setup 16k of stack }
  146. FStackSize:=16384;
  147. Getmem(FStackPointer,StackSize);
  148. inc(FStackPointer,StackSize);
  149. FCallExitProcess:=false;
  150. { Clone }
  151. FHandle:= Clone(@ThreadProc,FStackPointer,Flags,self);
  152. // if FSuspended then Suspend;
  153. FThreadID := FHandle;
  154. IsMultiThread := TRUE;
  155. FFatalException := nil;
  156. end;
  157. procedure TThread.SysDestroy;
  158. begin
  159. if not FFinished and not Suspended then
  160. begin
  161. Terminate;
  162. WaitFor;
  163. end;
  164. if FHandle <> -1 then
  165. fpkill(FHandle, SIGKILL);
  166. dec(FStackPointer,FStackSize);
  167. Freemem(FStackPointer);
  168. FFatalException.Free;
  169. FFatalException := nil;
  170. RemoveThread(self);
  171. end;
  172. procedure TThread.CallOnTerminate;
  173. begin
  174. FOnTerminate(Self);
  175. end;
  176. procedure TThread.DoTerminate;
  177. begin
  178. if Assigned(FOnTerminate) then
  179. Synchronize(@CallOnTerminate);
  180. end;
  181. const
  182. { I Don't know idle or timecritical, value is also 20, so the largest other
  183. possibility is 19 (PFV) }
  184. Priorities: array [TThreadPriority] of Integer =
  185. (-20,-19,-10,9,10,19,20);
  186. function TThread.GetPriority: TThreadPriority;
  187. var
  188. P: Integer;
  189. I: TThreadPriority;
  190. begin
  191. P := fpGetPriority(Prio_Process,FHandle);
  192. Result := tpNormal;
  193. for I := Low(TThreadPriority) to High(TThreadPriority) do
  194. if Priorities[I] = P then
  195. Result := I;
  196. end;
  197. procedure TThread.SetPriority(Value: TThreadPriority);
  198. begin
  199. fpSetPriority(Prio_Process,FHandle,Priorities[Value]);
  200. end;
  201. procedure TThread.Synchronize(Method: TThreadMethod);
  202. begin
  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. {BeOS implementation}
  282. function SemaphoreInit: Pointer;
  283. begin
  284. SemaphoreInit := GetMem(SizeOf(TFilDes));
  285. fppipe(PFilDes(SemaphoreInit)^);
  286. end;
  287. procedure SemaphoreWait(const FSem: Pointer);
  288. var
  289. b: byte;
  290. begin
  291. fpread(PFilDes(FSem)^[0], b, 1);
  292. end;
  293. procedure SemaphorePost(const FSem: Pointer);
  294. var
  295. b : byte;
  296. begin
  297. b := 0;
  298. fpwrite(PFilDes(FSem)^[1], b, 1);
  299. end;
  300. procedure SemaphoreDestroy(const FSem: Pointer);
  301. begin
  302. fpclose(PFilDes(FSem)^[0]);
  303. fpclose(PFilDes(FSem)^[1]);
  304. FreeMemory(FSem);
  305. end;
  306. // =========== semaphore end ===========
  307. var
  308. ThreadsInited: boolean = false;
  309. {$IFDEF LINUX}
  310. GMainPID: LongInt = 0;
  311. {$ENDIF}
  312. const
  313. // stupid, considering its not even implemented...
  314. Priorities: array [TThreadPriority] of Integer =
  315. (-20,-19,-10,0,9,18,19);
  316. procedure InitThreads;
  317. begin
  318. if not ThreadsInited then begin
  319. ThreadsInited := true;
  320. {$IFDEF LINUX}
  321. GMainPid := fpgetpid();
  322. {$ENDIF}
  323. end;
  324. end;
  325. procedure DoneThreads;
  326. begin
  327. ThreadsInited := false;
  328. end;
  329. { ok, so this is a hack, but it works nicely. Just never use
  330. a multiline argument with WRITE_DEBUG! }
  331. {$MACRO ON}
  332. {$IFDEF DEBUG_MT}
  333. {$define WRITE_DEBUG := writeln} // actually write something
  334. {$ELSE}
  335. {$define WRITE_DEBUG := //} // just comment out those lines
  336. {$ENDIF}
  337. function ThreadFunc(parameter: Pointer): LongInt; // cdecl;
  338. var
  339. LThread: TThread;
  340. c: char;
  341. begin
  342. WRITE_DEBUG('ThreadFunc is here...');
  343. LThread := TThread(parameter);
  344. {$IFDEF LINUX}
  345. // save the PID of the "thread"
  346. // this is different from the PID of the main thread if
  347. // the LinuxThreads implementation is used
  348. LThread.FPid := fpgetpid();
  349. {$ENDIF}
  350. WRITE_DEBUG('thread initing, parameter = ', LongInt(LThread));
  351. try
  352. if LThread.FInitialSuspended then begin
  353. SemaphoreWait(LThread.FSem);
  354. if not LThread.FInitialSuspended then begin
  355. WRITE_DEBUG('going into LThread.Execute');
  356. LThread.Execute;
  357. end;
  358. end else begin
  359. WRITE_DEBUG('going into LThread.Execute');
  360. LThread.Execute;
  361. end;
  362. except
  363. on e: exception do begin
  364. WRITE_DEBUG('got exception: ',e.message);
  365. LThread.FFatalException := TObject(AcquireExceptionObject);
  366. // not sure if we should really do this...
  367. // but .Destroy was called, so why not try FreeOnTerminate?
  368. if e is EThreadDestroyCalled then LThread.FFreeOnTerminate := true;
  369. end;
  370. end;
  371. WRITE_DEBUG('thread done running');
  372. Result := LThread.FReturnValue;
  373. WRITE_DEBUG('Result is ',Result);
  374. LThread.FFinished := True;
  375. LThread.DoTerminate;
  376. if LThread.FreeOnTerminate then begin
  377. WRITE_DEBUG('Thread should be freed');
  378. LThread.Free;
  379. WRITE_DEBUG('Thread freed');
  380. end;
  381. WRITE_DEBUG('thread func exiting');
  382. end;
  383. { TThread }
  384. procedure TThread.SysCreate(CreateSuspended: Boolean; const StackSize: SizeUInt);
  385. var
  386. data : pointer;
  387. begin
  388. // lets just hope that the user doesn't create a thread
  389. // via BeginThread and creates the first TThread Object in there!
  390. InitThreads;
  391. FSem := SemaphoreInit;
  392. FSuspended := CreateSuspended;
  393. FSuspendedExternal := false;
  394. FInitialSuspended := CreateSuspended;
  395. FFatalException := nil;
  396. WRITE_DEBUG('creating thread, self = ',longint(self));
  397. FHandle:= BeginThread(@ThreadFunc, Pointer(Self), FThreadID);
  398. WRITE_DEBUG('TThread.Create done');
  399. end;
  400. procedure TThread.SysDestroy;
  401. begin
  402. if FThreadID = GetCurrentThreadID then begin
  403. raise EThreadDestroyCalled.Create('A thread cannot destroy itself except by setting FreeOnTerminate and leaving!');
  404. end;
  405. // if someone calls .Free on a thread with
  406. // FreeOnTerminate, then don't crash!
  407. FFreeOnTerminate := false;
  408. if not FFinished and not FSuspended then begin
  409. Terminate;
  410. WaitFor;
  411. end;
  412. if (FInitialSuspended) then begin
  413. // thread was created suspended but never woken up.
  414. SemaphorePost(FSem);
  415. WaitFor;
  416. end;
  417. FFatalException.Free;
  418. FFatalException := nil;
  419. SemaphoreDestroy(FSem);
  420. end;
  421. procedure TThread.SetSuspended(Value: Boolean);
  422. begin
  423. if Value <> FSuspended then
  424. if Value then
  425. Suspend
  426. else
  427. Resume;
  428. end;
  429. procedure TThread.Suspend;
  430. begin
  431. if not FSuspended then begin
  432. if FThreadID = GetCurrentThreadID then begin
  433. FSuspended := true;
  434. SemaphoreWait(FSem);
  435. end else begin
  436. FSuspendedExternal := true;
  437. {$IFDEF LINUX}
  438. // naughty hack if the user doesn't have Linux with NPTL...
  439. // in that case, the PID of threads will not be identical
  440. // to the other threads, which means that our thread is a normal
  441. // process that we can suspend via SIGSTOP...
  442. // this violates POSIX, but is the way it works on the
  443. // LinuxThreads pthread implementation. Not with NPTL, but in that case
  444. // getpid(2) also behaves properly and returns the same PID for
  445. // all threads. Thats actually (FINALLY!) native thread support :-)
  446. if FPid <> GMainPID then begin
  447. FSuspended := true;
  448. fpkill(FPid, SIGSTOP);
  449. end;
  450. {$ELSE}
  451. SuspendThread(FHandle);
  452. {$ENDIF}
  453. end;
  454. end;
  455. end;
  456. procedure TThread.Resume;
  457. begin
  458. if (not FSuspendedExternal) then begin
  459. if FSuspended then begin
  460. SemaphorePost(FSem);
  461. FInitialSuspended := false;
  462. FSuspended := False;
  463. end;
  464. end else begin
  465. {$IFDEF LINUX}
  466. // see .Suspend
  467. if FPid <> GMainPID then begin
  468. fpkill(FPid, SIGCONT);
  469. FSuspended := False;
  470. end;
  471. {$ELSE}
  472. ResumeThread(FHandle);
  473. {$ENDIF}
  474. FSuspendedExternal := false;
  475. end;
  476. end;
  477. procedure TThread.Terminate;
  478. begin
  479. FTerminated := True;
  480. end;
  481. function TThread.WaitFor: Integer;
  482. begin
  483. WRITE_DEBUG('waiting for thread ',FHandle);
  484. WaitFor := WaitForThreadTerminate(FHandle, 0);
  485. WRITE_DEBUG('thread terminated');
  486. end;
  487. procedure TThread.CallOnTerminate;
  488. begin
  489. // no need to check if FOnTerminate <> nil, because
  490. // thats already done in DoTerminate
  491. FOnTerminate(self);
  492. end;
  493. procedure TThread.DoTerminate;
  494. begin
  495. if Assigned(FOnTerminate) then
  496. Synchronize(@CallOnTerminate);
  497. end;
  498. function TThread.GetPriority: TThreadPriority;
  499. var
  500. P: Integer;
  501. I: TThreadPriority;
  502. begin
  503. P := ThreadGetPriority(FHandle);
  504. Result := tpNormal;
  505. for I := Low(TThreadPriority) to High(TThreadPriority) do
  506. if Priorities[I] = P then
  507. Result := I;
  508. end;
  509. (*
  510. procedure TThread.Synchronize(Method: TThreadMethod);
  511. begin
  512. {$TODO someone with more clue of the GUI stuff will have to do this}
  513. end;
  514. *)
  515. procedure TThread.SetPriority(Value: TThreadPriority);
  516. begin
  517. ThreadSetPriority(FHandle, Priorities[Value]);
  518. end;
  519. {$ENDIF}