athreads.pp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302
  1. {
  2. This file is part of the Free Pascal run time library.
  3. Copyright (c) 2015 by Karoly Balogh,
  4. member of the Free Pascal development team.
  5. native threadmanager implementation for Amiga-like systems
  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. {$mode objfpc}
  13. unit athreads;
  14. interface
  15. procedure SetAThreadBaseName(s: String);
  16. function GetAThreadProcess(threadID: TThreadID): Pointer;
  17. implementation
  18. { enable this to compile athreads easily outside the RTL }
  19. {.$DEFINE ATHREADS_STANDALONE}
  20. {$IFDEF ATHREADS_STANDALONE}
  21. uses
  22. exec, amigados, utility;
  23. {$ELSE}
  24. { * Include required system specific includes * }
  25. {$include execd.inc}
  26. {$include execf.inc}
  27. {$include timerd.inc}
  28. {$include doslibd.inc}
  29. {$include doslibf.inc}
  30. {$ENDIF}
  31. const
  32. threadvarblocksize : dword = 0;
  33. var
  34. SubThreadBaseName: String = 'FPC Subthread';
  35. {.$define DEBUG_MT}
  36. {.$define DEBUG_AMIEVENT}
  37. type
  38. TThreadOperation = ( toNone, toStart, toResume, toExit );
  39. type
  40. PThreadMsg = ^TThreadMsg;
  41. PThreadInfo = ^TThreadInfo;
  42. TThreadInfo = record
  43. threadVars: Pointer; { have threadvars ptr as first field, so no offset is needed to access it (faster) }
  44. threadVarsSize: DWord; { size of the allocated threadvars block }
  45. nextThread: PThreadInfo; { threadinfos are a linked list, using this field }
  46. threadPtr: PProcess; { our thread pointer, as returned by CreateNewProc(). invalid after exited field is true! }
  47. threadID: TThreadID; { thread Unique ID }
  48. stackLen: PtrUInt; { stack size the thread was construced with }
  49. exitCode: Pointer; { exitcode after the process has exited }
  50. f: TThreadFunc; { ThreadFunc function pointer }
  51. p: Pointer; { ThreadFunc argument }
  52. flags: dword; { Flags this thread were created with }
  53. num: longint; { This was the "num"th thread to created }
  54. mainthread: boolean; { true if this is our main thread }
  55. exited: boolean; { true if the thread has exited, and can be cleaned up }
  56. startSuspended: boolean; { true if the thread was started suspended, and not resumed yet }
  57. suspended: boolean; { true if the thread is currently suspended }
  58. mutex: TSignalSemaphore; { thread's mutex. locked during the thread's life. }
  59. name: String; { Thread's name }
  60. end;
  61. TThreadMsg = record
  62. tm_MsgNode : TMessage;
  63. tm_ThreadInfo: PThreadInfo;
  64. tm_Operation : TThreadOperation;
  65. end;
  66. var
  67. AThreadManager: TThreadManager;
  68. AThreadList: PThreadInfo;
  69. AThreadListLen: LongInt;
  70. AThreadNum: LongInt;
  71. AThreadListSemaphore: TSignalSemaphore;
  72. { Simple IntToStr() replacement which works with ShortStrings }
  73. function IToStr(const i: LongInt): String;
  74. begin
  75. Str(I,result);
  76. end;
  77. {$IFDEF DEBUG_MT}
  78. function IToHStr(const i: LongInt): String;
  79. begin
  80. result:=HexStr(Pointer(i));
  81. end;
  82. {$ENDIF}
  83. { Function to add a thread to the running threads list }
  84. procedure AddToThreadList(var l: PThreadInfo; ti: PThreadInfo);
  85. var
  86. p : PThreadInfo;
  87. inList: Boolean;
  88. begin
  89. inList:=False;
  90. ObtainSemaphore(@AThreadListSemaphore);
  91. if l = nil then
  92. { if the list is not yet allocated, the newly added
  93. threadinfo will be the first item }
  94. l:=ti
  95. else
  96. begin
  97. { otherwise, look for the last item and append }
  98. p:=l;
  99. while (p^.nextThread<>nil) do p:=p^.nextThread;
  100. p^.nextThread:=ti;
  101. end;
  102. inc(AThreadNum);
  103. ti^.num:=AThreadNum;
  104. inc(AThreadListLen);
  105. {$IFDEF DEBUG_MT}
  106. SysDebugLn('FPC AThreads: thread ID:'+IToHStr(ti^.threadID)+' added, now '+IToStr(AThreadListLen)+' thread(s) in list.');
  107. {$ENDIF}
  108. ReleaseSemaphore(@AThreadListSemaphore);
  109. end;
  110. { Function to remove a thread from running threads list }
  111. function RemoveFromThreadList(var l: PThreadInfo; threadID: TThreadID): boolean;
  112. var
  113. p : PThreadInfo;
  114. pprev : PThreadInfo;
  115. inList : Boolean;
  116. tmpNext: PThreadInfo;
  117. tmpInfo: PThreadInfo;
  118. begin
  119. inList:=False;
  120. if l=nil then
  121. begin
  122. RemoveFromThreadList:=inList;
  123. exit;
  124. end;
  125. ObtainSemaphore(@AThreadListSemaphore);
  126. p:=l;
  127. pprev:=nil;
  128. while (p <> nil) and (p^.threadID <> threadID) do
  129. begin
  130. pprev:=p;
  131. p:=p^.nextThread;
  132. end;
  133. if p <> nil then
  134. begin
  135. tmpNext:=p^.nextThread;
  136. if not p^.mainthread and p^.exited then
  137. begin
  138. {$IFDEF DEBUG_MT}
  139. SysDebugLn('FPC AThreads: Releasing resources for thread ID:'+IToHStr(threadID));
  140. if (p^.threadVars <> nil) or (p^.threadVarsSize <> 0) then
  141. SysDebugLn('FPC AThreads: WARNING, threadvars area wasn''t properly freed!'+IToHStr(threadID));
  142. {$ENDIF}
  143. dispose(p);
  144. if pprev <> nil then
  145. pprev^.nextThread:=tmpNext;
  146. Dec(AThreadListLen);
  147. end
  148. else
  149. begin
  150. {$IFDEF DEBUG_MT}
  151. SysDebugLn('FPC AThreads: Error! Attempt to remove threadID, which is the mainthread or not exited:'+IToHStr(threadID));
  152. {$ENDIF}
  153. inList:=false;
  154. end;
  155. end
  156. {$IFDEF DEBUG_MT}
  157. else
  158. SysDebugLn('FPC AThreads: Error! Attempt to remove threadID, which is not in list:'+IToHstr(threadID))
  159. {$ENDIF}
  160. ;
  161. ReleaseSemaphore(@AThreadListSemaphore);
  162. RemoveFromThreadList:=inList;
  163. end;
  164. { Function to return a function's ThreadInfo based on the threadID }
  165. function GetThreadInfo(var l: PThreadInfo; threadID: TThreadID): PThreadInfo;
  166. var
  167. p : PThreadInfo;
  168. inList: Boolean;
  169. begin
  170. inList:=False;
  171. GetThreadInfo:=nil;
  172. if l = nil then
  173. exit;
  174. ObtainSemaphoreShared(@AThreadListSemaphore);
  175. p:=l;
  176. while (p <> nil) and (p^.threadID <> threadID) do
  177. p:=p^.nextThread;
  178. GetThreadInfo:=p;
  179. ReleaseSemaphore(@AThreadListSemaphore);
  180. end;
  181. { Get current thread's ThreadInfo structure }
  182. function GetCurrentThreadInfo: PThreadInfo;
  183. begin
  184. result:=PThreadInfo(PProcess(FindTask(nil))^.pr_Task.tc_UserData);
  185. end;
  186. { Returns the number of threads still not exited in our threadlist }
  187. function CountRunningThreads(var l: PThreadInfo): LongInt;
  188. var
  189. p: PThreadInfo;
  190. begin
  191. CountRunningThreads:=0;
  192. ObtainSemaphoreShared(@AThreadListSemaphore);
  193. p:=l;
  194. while p <> nil do
  195. begin
  196. inc(CountRunningThreads,ord(not p^.exited));
  197. p:=p^.nextThread;
  198. end;
  199. ReleaseSemaphore(@AThreadListSemaphore);
  200. end;
  201. { Helper function for IPC }
  202. procedure SendMessageToThread(var threadMsg: TThreadMsg; p: PThreadInfo; const op: TThreadOperation; waitReply: boolean);
  203. var
  204. replyPort: PMsgPort;
  205. begin
  206. replyPort:=@PProcess(FindTask(nil))^.pr_MsgPort;
  207. FillChar(threadMsg,sizeof(threadMsg),0);
  208. with threadMsg do
  209. begin
  210. with tm_MsgNode do
  211. begin
  212. mn_Node.ln_Type:=NT_MESSAGE;
  213. mn_Length:=SizeOf(TThreadMsg);
  214. if waitReply then
  215. mn_ReplyPort:=replyPort
  216. else
  217. mn_ReplyPort:=nil;
  218. end;
  219. tm_ThreadInfo:=p;
  220. tm_Operation:=op;
  221. end;
  222. PutMsg(@p^.threadPtr^.pr_MsgPort,@threadMsg);
  223. if waitReply then
  224. begin
  225. WaitPort(replyPort);
  226. GetMsg(replyPort);
  227. end;
  228. end;
  229. procedure SetAThreadBaseName(s: String);
  230. begin
  231. ObtainSemaphore(@AThreadListSemaphore);
  232. SubThreadBaseName:=s;
  233. ReleaseSemaphore(@AThreadListSemaphore);
  234. end;
  235. function GetAThreadBaseName: String;
  236. begin
  237. ObtainSemaphoreShared(@AThreadListSemaphore);
  238. GetAThreadBaseName:=SubThreadBaseName;
  239. ReleaseSemaphore(@AThreadListSemaphore);
  240. end;
  241. function GetAThreadProcess(threadID: TThreadID): Pointer;
  242. begin
  243. GetAThreadProcess:=nil;
  244. ObtainSemaphoreShared(@AThreadListSemaphore);
  245. with PThreadInfo(threadID)^ do
  246. begin
  247. if not exited then
  248. GetAThreadProcess:=threadPtr;
  249. end;
  250. ReleaseSemaphore(@AThreadListSemaphore);
  251. end;
  252. procedure AInitThreadvar(var offset : dword;size : dword);
  253. begin
  254. {$IFDEF DEBUG_MT}
  255. {SysDebugLn('FPC AThreads: InitThreadvar');}
  256. {$ENDIF}
  257. offset:=threadvarblocksize;
  258. inc(threadvarblocksize,size);
  259. end;
  260. function ARelocateThreadvar(offset : dword) : pointer;
  261. var
  262. p: PThreadInfo;
  263. begin
  264. {$IFDEF DEBUG_MT}
  265. {SysDebugLn('FPC AThreads: RelocateThreadvar');}
  266. {$ENDIF}
  267. p:=GetCurrentThreadInfo;
  268. if (p <> nil) and (p^.threadVars <> nil) then
  269. result:=p^.threadVars + Offset
  270. else
  271. result:=nil;
  272. end;
  273. procedure AAllocateThreadVars;
  274. var
  275. p: PThreadInfo;
  276. begin
  277. { we've to allocate the memory from system }
  278. { because the FPC heap management uses }
  279. { exceptions which use threadvars but }
  280. { these aren't allocated yet ... }
  281. { allocate room on the heap for the thread vars }
  282. p:=GetCurrentThreadInfo;
  283. if p <> nil then
  284. begin
  285. {$ifdef DEBUG_MT}
  286. SysDebugLn('FPC AThreads: Allocating threadvars, ID:'+IToHStr(p^.threadID));
  287. {$endif}
  288. {$ifdef AMIGA}
  289. ObtainSemaphore(ASYS_heapSemaphore);
  290. {$endif}
  291. p^.threadVars:=AllocPooled(ASYS_heapPool,threadvarblocksize);
  292. if p^.threadVars = nil then
  293. SysDebugLn('FPC AThreads: Failed to allocate threadvar memory!')
  294. else
  295. begin
  296. p^.threadVarsSize:=threadvarblocksize;
  297. FillChar(p^.threadVars^,threadvarblocksize,0);
  298. end;
  299. {$ifdef AMIGA}
  300. ReleaseSemaphore(ASYS_heapSemaphore);
  301. {$endif}
  302. end
  303. else
  304. begin
  305. {$ifdef DEBUG_MT}
  306. SysDebugLn('FPC AThreads: AllocateThreadVars: tc_UserData of this process was nil!')
  307. {$endif}
  308. end;
  309. end;
  310. procedure AReleaseThreadVars;
  311. var
  312. p: PThreadInfo;
  313. begin
  314. p:=GetCurrentThreadInfo;
  315. if (p <> nil) and (p^.threadVars <> nil) then
  316. begin
  317. {$ifdef DEBUG_MT}
  318. SysDebugLn('FPC AThreads: Releasing threadvars, ID:'+IToHStr(p^.threadID));
  319. {$endif}
  320. {$ifdef AMIGA}
  321. ObtainSemaphore(ASYS_heapSemaphore);
  322. {$endif}
  323. FreePooled(ASYS_heapPool,p^.threadVars,p^.threadVarsSize);
  324. p^.threadVars:=nil;
  325. p^.threadVarsSize:=0;
  326. {$ifdef AMIGA}
  327. ReleaseSemaphore(ASYS_heapSemaphore);
  328. {$endif}
  329. end
  330. else
  331. begin
  332. {$ifdef DEBUG_MT}
  333. SysDebugLn('FPC AThreads: ReleaseThreadVars: tc_UserData or threadVars area of this process was nil!')
  334. {$endif}
  335. end;
  336. end;
  337. procedure InitAThreading;
  338. var
  339. threadInfo: PThreadInfo;
  340. p: PProcess;
  341. begin
  342. if (InterLockedExchange(longint(IsMultiThread),ord(true)) = 0) then
  343. begin
  344. { We're still running in single thread mode, setup the TLS }
  345. {$ifdef DEBUG_MT}
  346. SysDebugLn('FPC AThreads: Entering multithreaded mode...');
  347. {$endif}
  348. p:=PProcess(FindTask(nil));
  349. new(threadInfo);
  350. FillChar(threadInfo^,sizeof(TThreadInfo),0);
  351. p^.pr_Task.tc_UserData:=threadInfo;
  352. threadInfo^.mainThread:=true;
  353. InitSemaphore(@threadInfo^.mutex);
  354. ObtainSemaphore(@threadInfo^.mutex);
  355. threadInfo^.threadPtr:=p;
  356. threadInfo^.threadID:=TThreadID(threadInfo);
  357. InitThreadVars(@ARelocateThreadvar);
  358. AddToThreadList(AThreadList,threadInfo);
  359. end;
  360. end;
  361. procedure ThreadFunc; cdecl;
  362. var
  363. thisThread: PProcess;
  364. threadMsg: PThreadMsg;
  365. resumeMsg: PThreadMsg;
  366. exitSuspend: boolean; // true if we have to exit instead of resuming
  367. threadInfo: PThreadInfo;
  368. begin
  369. thisThread:=PProcess(FindTask(nil));
  370. { wait for our start message to arrive, then fetch it }
  371. WaitPort(@thisThread^.pr_MsgPort);
  372. threadMsg:=PThreadMsg(GetMsg(@thisThread^.pr_MsgPort));
  373. { fetch existing threadinfo from the start message, and set
  374. it to tc_userData, so we can proceed with threadvars }
  375. threadInfo:=threadMsg^.tm_ThreadInfo;
  376. thisThread^.pr_Task.tc_userData:=threadInfo;
  377. {$ifdef DEBUG_MT}
  378. SysDebugLn('FPC AThreads: Entering subthread function, ID:'+hexStr(threadInfo));
  379. {$endif}
  380. { Obtain the threads' mutex, used for exit sync }
  381. ObtainSemaphore(@threadInfo^.mutex);
  382. { Allocate local thread vars, this must be the first thing,
  383. because the exception management and io depends on threadvars }
  384. AAllocateThreadVars;
  385. { Rename the thread into something sensible }
  386. if threadInfo^.name <> '' then
  387. begin
  388. {$ifdef DEBUG_MT}
  389. { this line can't be before threadvar allocation }
  390. SysDebugLn('FPC AThreads: Renaming thread ID:'+hexStr(threadInfo)+' to '+threadInfo^.name);
  391. {$endif}
  392. thisThread^.pr_Task.tc_Node.ln_Name:=PChar(@threadInfo^.name[1]);
  393. end;
  394. { Reply the message, so the calling thread could continue }
  395. { note that threadMsg was allocated on the caller's task, so }
  396. { it will be invalid below this point }
  397. ReplyMsg(PMessage(threadMsg));
  398. { if creating a suspended thread, wait for the wakeup message to arrive }
  399. { then check if we actually have to resume, or exit }
  400. exitSuspend:=false;
  401. if threadInfo^.startSuspended then
  402. begin
  403. {$ifdef DEBUG_MT}
  404. SysDebugLn('FPC AThreads: Suspending subthread on entry, ID:'+hexStr(threadInfo));
  405. {$endif}
  406. WaitPort(@thisThread^.pr_MsgPort);
  407. resumeMsg:=PThreadMsg(GetMsg(@thisThread^.pr_MsgPort));
  408. exitSuspend:=resumeMsg^.tm_Operation <> toResume;
  409. threadInfo^.startSuspended:=false;
  410. ReplyMsg(PMessage(resumeMsg));
  411. {$ifdef DEBUG_MT}
  412. SysDebugLn('FPC AThreads: Resuming subthread on entry, ID:'+hexStr(threadInfo)+', resumed only to exit: '+IToStr(ord(exitSuspend)));
  413. {$endif}
  414. end;
  415. { Finally, call the user code }
  416. if not exitSuspend then
  417. begin
  418. InitThread(threadInfo^.stackLen);
  419. DoThreadInitProcChain;
  420. threadInfo^.exitCode:=Pointer(threadInfo^.f(threadInfo^.p));
  421. DoThreadExitProcChain;
  422. DoneThread;
  423. end;
  424. {$ifdef DEBUG_MT}
  425. SysDebugLn('FPC AThreads: Exiting Subthread function, ID:'+hexStr(threadInfo));
  426. {$endif}
  427. Forbid();
  428. threadInfo^.exited:=true;
  429. threadInfo^.threadPtr:=nil;
  430. { Finally, Release our exit mutex. }
  431. ReleaseSemaphore(@threadInfo^.mutex);
  432. end;
  433. function CreateNewProcess(const Tags : Array Of PtrUInt) : PProcess;
  434. begin
  435. result:=CreateNewProc(@Tags[0]);
  436. end;
  437. function ABeginThread(sa : Pointer;stacksize : PtrUInt;
  438. ThreadFunction : tthreadfunc;p : pointer;
  439. creationFlags : dword; var ThreadId : TThreadId) : TThreadID;
  440. var
  441. threadInfo: PThreadInfo;
  442. threadMsg: TThreadMsg;
  443. threadName: String;
  444. subThread: PProcess;
  445. begin
  446. ABeginThread:=TThreadID(0);
  447. {$ifdef DEBUG_MT}
  448. SysDebugLn('FPC AThreads: Creating new thread...');
  449. {$endif DEBUG_MT}
  450. { Initialize multithreading if not done }
  451. if not IsMultiThread then
  452. InitAThreading;
  453. { the only way to pass data to the newly created thread
  454. in a MT safe way, is to use the heap }
  455. new(threadInfo);
  456. FillChar(threadInfo^,sizeof(TThreadInfo),0);
  457. InitSemaphore(@threadInfo^.mutex);
  458. threadInfo^.f:=ThreadFunction;
  459. threadInfo^.p:=p;
  460. if (creationFlags and STACK_SIZE_PARAM_IS_A_RESERVATION) > 0 then
  461. threadInfo^.stackLen:=stacksize
  462. else
  463. threadInfo^.stackLen:=System.StackLength; { inherit parent's stack size }
  464. threadInfo^.startSuspended:=(creationFlags and CREATE_SUSPENDED) > 0;
  465. {$ifdef DEBUG_MT}
  466. SysDebugLn('FPC AThreads: Starting new thread... Stack size: '+IToStr(threadInfo^.stackLen));
  467. {$endif}
  468. subThread:=CreateNewProcess([NP_Entry,PtrUInt(@ThreadFunc),
  469. {$IFDEF MORPHOS}
  470. NP_CodeType,CODETYPE_PPC,
  471. NP_PPCStackSize,threadInfo^.stacklen,
  472. {$ELSE}
  473. NP_StackSize,threadInfo^.stacklen,
  474. {$ENDIF}
  475. TAG_DONE]);
  476. if subThread = nil then
  477. begin
  478. {$ifdef DEBUG_MT}
  479. SysDebugLn('FPC AThreads: Failed to start the subthread!');
  480. {$endif}
  481. exit;
  482. end;
  483. ThreadID:=TThreadID(threadInfo);
  484. threadInfo^.threadPtr:=subThread;
  485. threadInfo^.threadID:=ThreadID;
  486. AddToThreadList(AThreadList,threadInfo);
  487. { the thread should be started, and waiting for our start message, so send it }
  488. {$ifdef DEBUG_MT}
  489. SysDebugLn('FPC AThreads: Sending start message to subthread and waiting for reply, ID:'+IToHStr(threadID));
  490. {$endif}
  491. { AddToThreadList assigned us a number, so use it to name the thread }
  492. threadInfo^.name:=GetAThreadBaseName+' #'+IToStr(threadInfo^.num);
  493. SendMessageToThread(threadMsg,threadInfo,toStart,true);
  494. ABeginThread:=ThreadId;
  495. {$ifdef DEBUG_MT}
  496. SysDebugLn('FPC AThreads: Thread created successfully, ID:'+IToHStr(threadID));
  497. {$endif}
  498. end;
  499. procedure AEndThread(ExitCode : DWord);
  500. begin
  501. { Do not call DoneThread here. It will be called by the threadfunction, when it exits. }
  502. end;
  503. function ASuspendThread (threadHandle : TThreadID) : dword;
  504. var
  505. p: PThreadInfo;
  506. m: PThreadMsg;
  507. begin
  508. ASuspendThread:=0;
  509. if GetCurrentThreadID = threadHandle then
  510. begin
  511. p:=GetThreadInfo(AThreadList,threadHandle);
  512. if p <> nil then
  513. begin
  514. p^.suspended:=true;
  515. while p^.suspended do
  516. begin
  517. WaitPort(@p^.threadPtr^.pr_MsgPort);
  518. m:=PThreadMsg(GetMsg(@p^.threadPtr^.pr_MsgPort));
  519. if m^.tm_Operation = toResume then
  520. p^.suspended:=false
  521. else
  522. {$ifdef DEBUG_MT}
  523. SysDebugLn('FPC AThreads: Got message during suspend, but it wasn''t toResume! ID:'+IToHStr(threadHandle))
  524. {$endif}
  525. ;
  526. ReplyMsg(PMessage(m));
  527. end;
  528. end;
  529. end
  530. else
  531. begin
  532. {$ifdef DEBUG_MT}
  533. SysDebugLn('FPC AThreads: SuspendThread called for ID:'+IToHStr(threadHandle)+' which is not the current thread!');
  534. {$endif}
  535. result:=dword(-1);
  536. end;
  537. end;
  538. function AResumeThread (threadHandle : TThreadID) : dword;
  539. var
  540. m: TThreadMsg;
  541. p: PThreadInfo;
  542. begin
  543. AResumeThread:=0;
  544. Forbid();
  545. p:=GetThreadInfo(AThreadList,threadHandle);
  546. if (p <> nil) and (p^.suspended or p^.startSuspended) then
  547. begin
  548. {$ifdef DEBUG_MT}
  549. SysDebugLn('FPC AThreads: Waiting for thread to resume, ID:'+IToHStr(threadHandle));
  550. {$endif}
  551. { WaitPort in SendMessageToThread will break the Forbid() state... }
  552. SendMessageToThread(m,p,toResume,true);
  553. AResumeThread:=0;
  554. end
  555. else
  556. begin
  557. {$ifdef DEBUG_MT}
  558. SysDebugLn('FPC AThreads: Error, attempt to resume a non-suspended thread, or invalid thread ID:'+IToHStr(threadHandle));
  559. {$endif}
  560. AResumeThread:=dword(-1);
  561. end;
  562. Permit();
  563. end;
  564. procedure AThreadSwitch; {give time to other threads}
  565. begin
  566. { On Unix, this calls sched_yield();
  567. Harry 'Piru' Sintonen recommended to emulate this on Amiga systems with
  568. exec/Forbid-exec/Permit pair which is pretty fast to execute and will
  569. trigger a rescheduling.
  570. Another idea by Frank Mariak was to use exec/SetTaskPri() with the same
  571. priority }
  572. Forbid();
  573. Permit();
  574. end;
  575. function AKillThread (threadHandle : TThreadID) : dword;
  576. begin
  577. {$ifdef DEBUG_MT}
  578. SysDebugLn('FPC AThreads: unsupported operation: KillThread called for ID:'+IToHStr(threadHandle));
  579. {$endif}
  580. // cannot be properly supported on Amiga
  581. AKillThread:=dword(-1);
  582. end;
  583. function ACloseThread (threadHandle : TThreadID) : dword;
  584. begin
  585. {$WARNING The return value here seems to be undocumented}
  586. RemoveFromThreadList(AThreadList, threadHandle);
  587. result:=0;
  588. end;
  589. function AWaitForThreadTerminate (threadHandle : TThreadID; TimeoutMs : longint) : dword; {0=no timeout}
  590. var
  591. p: PThreadInfo;
  592. m: TThreadMsg;
  593. begin
  594. {.$WARNING Support for timeout argument is not implemented}
  595. { But since CThreads uses pthread_join, which has also no timeout,
  596. I don't think this is a big issue. (KB) }
  597. AWaitForThreadTerminate:=0;
  598. Forbid();
  599. p:=GetThreadInfo(AThreadList,threadHandle);
  600. if (p <> nil) then
  601. begin
  602. if not p^.exited then
  603. begin
  604. {$ifdef DEBUG_MT}
  605. SysDebugLn('FPC AThreads: Waiting for thread to exit, ID:'+IToHStr(threadHandle));
  606. {$endif}
  607. { WaitPort in SendMessageToThread will break the Forbid() state... }
  608. if p^.startSuspended then
  609. begin
  610. SendMessageToThread(m,p,toExit,true);
  611. {$ifdef DEBUG_MT}
  612. SysDebugLn('FPC AThreads: Signaled start-suspended thread to exit, ID:'+IToHStr(threadHandle));
  613. {$endif}
  614. end;
  615. { Wait for the thread to exit... }
  616. Permit();
  617. ObtainSemaphore(@p^.mutex);
  618. ReleaseSemaphore(@p^.mutex);
  619. Forbid();
  620. end
  621. else
  622. {$ifdef DEBUG_MT}
  623. SysDebugLn('FPC AThreads: Thread already exited, ID:'+IToHStr(threadHandle));
  624. {$endif}
  625. AWaitForThreadTerminate:=DWord(p^.exitCode);
  626. end
  627. else
  628. begin
  629. {$ifdef DEBUG_MT}
  630. SysDebugLn('FPC AThreads: Error, attempt to wait for invalid thread ID to exit, ID:'+IToHStr(threadHandle));
  631. {$endif}
  632. AWaitForThreadTerminate:=dword(-1); { Return non-zero code on error. }
  633. end;
  634. Permit();
  635. end;
  636. function AThreadSetPriority (threadHandle : TThreadID; Prio: longint): boolean; {-15..+15, 0=normal}
  637. begin
  638. {$Warning ThreadSetPriority needs to be implemented}
  639. result:=false;
  640. end;
  641. function AThreadGetPriority (threadHandle : TThreadID): Integer;
  642. begin
  643. {$Warning ThreadGetPriority needs to be implemented}
  644. result:=0;
  645. end;
  646. function AGetCurrentThreadId : TThreadID;
  647. begin
  648. AGetCurrentThreadId := TThreadID(GetCurrentThreadInfo);
  649. end;
  650. Type PINTRTLEvent = ^TINTRTLEvent;
  651. TINTRTLEvent = record
  652. isset: boolean;
  653. end;
  654. Function intRTLEventCreate: PRTLEvent;
  655. var p:pintrtlevent;
  656. begin
  657. new(p);
  658. result:=PRTLEVENT(p);
  659. end;
  660. procedure intRTLEventDestroy(AEvent: PRTLEvent);
  661. var p:pintrtlevent;
  662. begin
  663. p:=pintrtlevent(aevent);
  664. dispose(p);
  665. end;
  666. procedure intRTLEventSetEvent(AEvent: PRTLEvent);
  667. var p:pintrtlevent;
  668. begin
  669. p:=pintrtlevent(aevent);
  670. p^.isset:=true;
  671. end;
  672. procedure intRTLEventResetEvent(AEvent: PRTLEvent);
  673. var p:pintrtlevent;
  674. begin
  675. p:=pintrtlevent(aevent);
  676. p^.isset:=false;
  677. end;
  678. procedure intRTLEventWaitFor(AEvent: PRTLEvent);
  679. var p:pintrtlevent;
  680. begin
  681. p:=pintrtlevent(aevent);
  682. p^.isset:=false;
  683. end;
  684. procedure intRTLEventWaitForTimeout(AEvent: PRTLEvent;timeout : longint);
  685. var
  686. p : pintrtlevent;
  687. begin
  688. p:=pintrtlevent(aevent);
  689. end;
  690. procedure AInitCriticalSection(var CS);
  691. begin
  692. {$IFDEF DEBUG_MT}
  693. SysDebugLn('FPC AThreads: InitCriticalSection '+hexStr(@CS));
  694. {$ENDIF}
  695. InitSemaphore(PSignalSemaphore(@CS));
  696. end;
  697. procedure AEnterCriticalSection(var CS);
  698. begin
  699. {$IFDEF DEBUG_MT}
  700. SysDebugLn('FPC AThreads: EnterCriticalSection '+hexStr(@CS));
  701. {$ENDIF}
  702. ObtainSemaphore(PSignalSemaphore(@CS));
  703. end;
  704. function ATryEnterCriticalSection(var CS):longint;
  705. begin
  706. {$IFDEF DEBUG_MT}
  707. SysDebugLn('FPC AThreads: TryEnterCriticalSection '+hexStr(@CS));
  708. {$ENDIF}
  709. result:=DWord(AttemptSemaphore(PSignalSemaphore(@CS)));
  710. if result<>0 then
  711. result:=1;
  712. end;
  713. procedure ALeaveCriticalSection(var CS);
  714. begin
  715. {$IFDEF DEBUG_MT}
  716. SysDebugLn('FPC AThreads: LeaveCriticalSection '+hexStr(@CS));
  717. {$ENDIF}
  718. ReleaseSemaphore(PSignalSemaphore(@CS));
  719. end;
  720. procedure ADoneCriticalSection(var CS);
  721. begin
  722. {$IFDEF DEBUG_MT}
  723. SysDebugLn('FPC AThreads: DoneCriticalSection '+hexStr(@CS));
  724. {$ENDIF}
  725. { unlock as long as unlocking works to unlock it if it is recursive
  726. some Delphi code might call this function with a locked mutex }
  727. with TSignalSemaphore(CS) do
  728. while ss_NestCount > 0 do
  729. ReleaseSemaphore(PSignalSemaphore(@CS));
  730. end;
  731. // Event Stuff
  732. // Return values for WaitFor
  733. const
  734. wrSignaled = 0;
  735. wrTimeout = 1;
  736. wrAbandoned = 2;
  737. wrError = 3;
  738. // the internal AmigaEvent
  739. type
  740. TAmiEvent = record
  741. IsSet: Boolean; // the actual Event setting
  742. Manual: Boolean; // do not automatically reset the event
  743. Name: string; // Name for the event structure (needed for cross process)
  744. Waiter: Integer; // number of WaitFor waiting for this event
  745. Destroyed: Boolean; // the event is going to be destroyed, all WaitFor please leave first
  746. Sem: TSignalSemaphore; // Semaphore to protect the whole stuff
  747. end;
  748. PAmiEvent = ^TAmiEvent;
  749. // Create an Event
  750. function intBasicEventCreate(EventAttributes : Pointer;
  751. AManualReset,InitialState : Boolean;const Name : ansistring):pEventState;
  752. var
  753. AmiEvent: PAmiEvent;
  754. begin
  755. New(AmiEvent);
  756. AmiEvent^.isSet := InitialState;
  757. AmiEvent^.Name := Name;
  758. AmiEvent^.Waiter := 0;
  759. AmiEvent^.Manual := AManualReset;
  760. AmiEvent^.Destroyed := False;
  761. InitSemaphore(@AmiEvent^.Sem);
  762. Result := AmiEvent;
  763. end;
  764. procedure intbasiceventdestroy(state:peventstate);
  765. var
  766. AmiEvent: PAmiEvent absolute State;
  767. Waiter: Integer;
  768. begin
  769. if Assigned(AmiEvent) then
  770. begin
  771. ObtainSemaphore(@AmiEvent^.Sem);
  772. AmiEvent^.Destroyed := True; // we destroy the event
  773. ReleaseSemaphore(@AmiEvent^.Sem);
  774. repeat
  775. DosDelay(1);
  776. until AmiEvent^.Waiter <= 0;
  777. ObtainSemaphore(@AmiEvent^.Sem); // is there anyone still waiting for it?
  778. ReleaseSemaphore(@AmiEvent^.Sem);
  779. Dispose(AmiEvent);
  780. end;
  781. end;
  782. procedure intbasiceventResetEvent(state:peventstate);
  783. var
  784. AmiEvent: PAmiEvent absolute State;
  785. begin
  786. if Assigned(AmiEvent) then
  787. begin
  788. {$IFDEF DEBUG_AMIEVENT}
  789. SysDebugLn('AmiEvent: Reset Event');
  790. {$ENDIF}
  791. ObtainSemaphore(@AmiEvent^.Sem);
  792. AmiEvent^.IsSet := False;
  793. ReleaseSemaphore(@AmiEvent^.Sem);
  794. end;
  795. end;
  796. procedure intbasiceventSetEvent(state:peventstate);
  797. var
  798. AmiEvent: PAmiEvent absolute State;
  799. begin
  800. if Assigned(AmiEvent) then
  801. begin
  802. {$IFDEF DEBUG_AMIEVENT}
  803. SysDebugLn('AmiEvent: Set Event');
  804. {$ENDIF}
  805. ObtainSemaphore(@AmiEvent^.Sem);
  806. AmiEvent^.IsSet := True;
  807. ReleaseSemaphore(@AmiEvent^.Sem);
  808. end;
  809. end;
  810. // Timer stuff
  811. procedure NewList(List: PList); inline;
  812. begin
  813. with List^ do
  814. begin
  815. lh_Head := PNode(@lh_Tail);
  816. lh_Tail := nil;
  817. lh_TailPred := PNode(@lh_Head)
  818. end;
  819. end;
  820. function CreatePort(Name: PChar; Pri: LongInt): PMsgPort;
  821. var
  822. SigBit: ShortInt;
  823. Port: PMsgPort;
  824. begin
  825. Sigbit := AllocSignal(-1);
  826. if sigbit = -1 then
  827. CreatePort := nil;
  828. Port := ExecAllocMem(SizeOf(TMsgPort), MEMF_CLEAR);
  829. if Port = nil then
  830. begin
  831. FreeSignal(SigBit);
  832. CreatePort := nil;
  833. end;
  834. with port^ do
  835. begin
  836. if Assigned(Name) then
  837. mp_Node.ln_Name := Name
  838. else
  839. mp_Node.ln_Name := nil;
  840. mp_Node.ln_Pri := pri;
  841. mp_Node.ln_Type := 4;
  842. mp_Flags := 0;
  843. mp_SigBit := SigBit;
  844. mp_SigTask := FindTask(nil);
  845. end;
  846. if Assigned(Name) then
  847. AddPort(Port)
  848. else
  849. NewList(Addr(Port^.mp_MsgList));
  850. CreatePort := Port;
  851. end;
  852. procedure DeletePort(Port: PMsgPort);
  853. begin
  854. if port <> nil then
  855. begin
  856. if Port^.mp_Node.ln_Name <> nil then
  857. RemPort(Port);
  858. Port^.mp_Node.ln_Type := $FF;
  859. Port^.mp_MsgList.lh_Head := PNode(-1);
  860. FreeSignal(Port^.mp_SigBit);
  861. ExecFreeMem(Port, SizeOf(TMsgPort));
  862. end;
  863. end;
  864. function CreateExtIO(Port: PMsgPort; Size: LongInt): PIORequest;
  865. begin
  866. Result := nil;
  867. if Port <> nil then
  868. begin
  869. Result := ExecAllocMem(Size, MEMF_CLEAR);
  870. if Result <> nil then
  871. begin
  872. Result^.io_Message.mn_Node.ln_Type := 7;
  873. Result^.io_Message.mn_Length := Size;
  874. Result^.io_Message.mn_ReplyPort := Port;
  875. end;
  876. end;
  877. end;
  878. procedure DeleteExtIO (IoReq: PIORequest);
  879. begin
  880. if IoReq <> nil then
  881. begin
  882. IoReq^.io_Message.mn_Node.ln_Type := $FF;
  883. IoReq^.io_Message.mn_ReplyPort := PMsgPort(-1);
  884. IoReq^.io_Device := PDevice(-1);
  885. ExecFreeMem(IoReq, IoReq^.io_Message.mn_Length);
  886. end
  887. end;
  888. function Create_Timer(TheUnit: LongInt): PTimeRequest;
  889. var
  890. TimerPort: PMsgPort;
  891. begin
  892. Result := nil;
  893. TimerPort := CreatePort(nil, 0);
  894. if TimerPort = nil then
  895. Exit;
  896. Result := PTimeRequest(CreateExtIO(TimerPort, SizeOf(TTimeRequest)));
  897. if Result = Nil then
  898. begin
  899. DeletePort(TimerPort);
  900. Exit;
  901. end;
  902. if OpenDevice(TIMERNAME, TheUnit, PIORequest(Result), 0) <> 0 then
  903. begin
  904. DeleteExtIO(PIORequest(Result));
  905. DeletePort(TimerPort);
  906. Result := nil;
  907. end;
  908. end;
  909. Procedure Delete_Timer(WhichTimer: PTimeRequest);
  910. var
  911. WhichPort: PMsgPort;
  912. begin
  913. WhichPort := WhichTimer^.tr_Node.io_Message.mn_ReplyPort;
  914. if assigned(WhichTimer) then
  915. begin
  916. CloseDevice(PIORequest(WhichTimer));
  917. DeleteExtIO(PIORequest(WhichTimer));
  918. end;
  919. if Assigned(WhichPort) then
  920. DeletePort(WhichPort);
  921. end;
  922. function GetEventTime(TR: PTimeRequest): Int64;
  923. begin
  924. Result := -1;
  925. if tr = nil then
  926. Exit;
  927. tr^.tr_node.io_Command := TR_GETSYSTIME;
  928. DoIO(PIORequest(tr));
  929. // structure assignment
  930. Result := Int64(tr^.tr_time.TV_Secs) * 1000 + tr^.tr_time.TV_Micro div 1000;
  931. end;
  932. // End timer stuff
  933. // the mighty Waitfor routine
  934. function intbasiceventWaitFor(Timeout : Cardinal;state:peventstate) : longint;
  935. var
  936. AmiEvent: PAmiEvent absolute State;
  937. Tr: PTimeRequest = nil;
  938. StartTime, CurTime: Int64;
  939. begin
  940. {$IFDEF DEBUG_AMIEVENT}
  941. SysDebugLn('AmiEvent: Enter WaitFor');
  942. {$ENDIF}
  943. Result := wrError;
  944. if Assigned(AmiEvent) then
  945. begin
  946. // we do an initial Check
  947. ObtainSemaphore(@AmiEvent^.Sem);
  948. if AmiEvent^.Destroyed then
  949. begin
  950. Result := wrAbandoned; // we got destroyed, so we just leave
  951. {$IFDEF DEBUG_AMIEVENT}
  952. SysDebugLn('AmiEvent: WaitFor Early Destroy');
  953. {$ENDIF}
  954. Exit;
  955. end;
  956. if AmiEvent^.IsSet then
  957. begin
  958. Result := wrSignaled; // signal Already set
  959. if not AmiEvent^.Manual then
  960. AmiEvent^.IsSet := False;
  961. {$IFDEF DEBUG_AMIEVENT}
  962. SysDebugLn('AmiEvent: WaitFor Early Signaled');
  963. {$ENDIF}
  964. Exit;
  965. end;
  966. // signal not set, so we add this call to the waiterlist
  967. Inc(AmiEvent^.Waiter);
  968. ReleaseSemaphore(@AmiEvent^.Sem);
  969. // that means we have to wait and care about the timeout -> need a timer
  970. Tr := create_timer(UNIT_MICROHZ);
  971. if not Assigned(Tr) then // cannot create timer :-O
  972. Exit;
  973. // time we started the actual waiting
  974. StartTime := GetEventTime(TR);
  975. try
  976. // the main loop, notice the breaks are inside the Obtain/Release
  977. // therefore the finally block must release it, (and no other exit allowed!)
  978. repeat
  979. CurTime := GetEventTime(TR); // to check the timeout, outside obtain/release to save some time
  980. ObtainSemaphore(@AmiEvent^.Sem);
  981. // check the status of event
  982. if AmiEvent^.Destroyed then
  983. begin
  984. Result := wrAbandoned; // we got destroyed
  985. {$IFDEF DEBUG_AMIEVENT}
  986. SysDebugLn('AmiEvent: WaitFor Destroy');
  987. {$ENDIF}
  988. break;
  989. end;
  990. if AmiEvent^.IsSet then
  991. begin
  992. Result := wrSignaled; // signal got set
  993. {$IFDEF DEBUG_AMIEVENT}
  994. SysDebugLn('AmiEvent: WaitFor Signaled');
  995. {$ENDIF}
  996. Break;
  997. end;
  998. if CurTime - StartTime > Timeout then
  999. begin
  1000. Result := wrTimeOut; // we got a timeout
  1001. {$IFDEF DEBUG_AMIEVENT}
  1002. SysDebugLn('AmiEvent: WaitFor TimeOut');
  1003. {$ENDIF}
  1004. Break;
  1005. end;
  1006. // if we reach here, nothing happend...
  1007. // we release the semaphore and wait for other threads to do something
  1008. ReleaseSemaphore(@AmiEvent^.Sem);
  1009. DosDelay(1);
  1010. until False;
  1011. finally
  1012. // reset the Event if needed
  1013. if (Result = wrSignaled) and (not AmiEvent^.Manual) then
  1014. AmiEvent^.IsSet := False;
  1015. // we finished so get us away from waiter list
  1016. Dec(AmiEvent^.Waiter);
  1017. ReleaseSemaphore(@AmiEvent^.Sem); // unlock the event
  1018. Delete_timer(tr); // timer not needed anymore
  1019. end;
  1020. end;
  1021. {$IFDEF DEBUG_AMIEVENT}
  1022. SysDebugLn('AmiEvent: Leave WaitFor');
  1023. {$ENDIF}
  1024. end;
  1025. // end Event stuff
  1026. function AInitThreads : Boolean;
  1027. begin
  1028. {$ifdef DEBUG_MT}
  1029. SysDebugLn('FPC AThreads: Entering InitThreads...');
  1030. {$endif}
  1031. result:=true;
  1032. // We assume that if you set the thread manager, the application is multithreading.
  1033. InitAThreading;
  1034. ThreadID := TThreadID(GetCurrentThreadInfo);
  1035. end;
  1036. function ADoneThreads : Boolean;
  1037. begin
  1038. result:=true;
  1039. end;
  1040. procedure SetAThreadManager;
  1041. begin
  1042. with AThreadManager do begin
  1043. InitManager :=@AInitThreads;
  1044. DoneManager :=@ADoneThreads;
  1045. BeginThread :=@ABeginThread;
  1046. EndThread :=@AEndThread;
  1047. SuspendThread :=@ASuspendThread;
  1048. ResumeThread :=@AResumeThread;
  1049. KillThread :=@AKillThread;
  1050. ThreadSwitch :=@AThreadSwitch;
  1051. CloseThread :=@ACloseThread;
  1052. WaitForThreadTerminate :=@AWaitForThreadTerminate;
  1053. ThreadSetPriority :=@AThreadSetPriority;
  1054. ThreadGetPriority :=@AThreadGetPriority;
  1055. GetCurrentThreadId :=@AGetCurrentThreadId;
  1056. InitCriticalSection :=@AInitCriticalSection;
  1057. DoneCriticalSection :=@ADoneCriticalSection;
  1058. EnterCriticalSection :=@AEnterCriticalSection;
  1059. TryEnterCriticalSection:=@ATryEnterCriticalSection;
  1060. LeaveCriticalSection :=@ALeaveCriticalSection;
  1061. InitThreadVar :=@AInitThreadVar;
  1062. RelocateThreadVar :=@ARelocateThreadVar;
  1063. AllocateThreadVars :=@AAllocateThreadVars;
  1064. ReleaseThreadVars :=@AReleaseThreadVars;
  1065. BasicEventCreate :=@intBasicEventCreate;
  1066. BasicEventDestroy :=@intBasicEventDestroy;
  1067. BasicEventResetEvent :=@intBasicEventResetEvent;
  1068. BasicEventSetEvent :=@intBasicEventSetEvent;
  1069. BasiceventWaitFor :=@intBasicEventWaitFor;
  1070. rtlEventCreate :=@intrtlEventCreate;
  1071. rtlEventDestroy :=@intrtlEventDestroy;
  1072. rtlEventSetEvent :=@intrtlEventSetEvent;
  1073. rtlEventResetEvent :=@intrtlEventResetEvent;
  1074. rtleventWaitForTimeout :=@intrtleventWaitForTimeout;
  1075. rtleventWaitFor :=@intrtleventWaitFor;
  1076. end;
  1077. SetThreadManager(AThreadManager);
  1078. end;
  1079. Procedure InitSystemThreads; external name '_FPC_InitSystemThreads';
  1080. { This should only be called from the finalization }
  1081. procedure WaitForAllThreads;
  1082. var
  1083. p: PThreadInfo;
  1084. pn: PThreadInfo;
  1085. begin
  1086. { If we are the main thread exiting, we have to wait for our subprocesses to
  1087. exit. Because AmigaOS won't clean up for us. Also, after exiting the main
  1088. thread the OS unloads all the code segments with code potentially still
  1089. running in the background... So even waiting here forever is better than
  1090. exiting with active threads, which will most likely just kill the OS
  1091. immediately. (KB) }
  1092. ObtainSemaphore(@AThreadListSemaphore);
  1093. {$IFDEF DEBUG_MT}
  1094. if AThreadListLen > 1 then
  1095. begin
  1096. SysDebugLn('FPC AThreads: We have registered subthreads, checking their status...');
  1097. if CountRunningThreads(AThreadList) > 1 then
  1098. SysDebugLn('FPC AThreads: We have running subthreads, waiting for them to exit...');
  1099. end;
  1100. {$ENDIF}
  1101. while CountRunningThreads(AThreadList) > 1 do
  1102. begin
  1103. ReleaseSemaphore(@AThreadListSemaphore);
  1104. DOSDelay(1);
  1105. { Reobtain the semaphore... }
  1106. ObtainSemaphore(@AThreadListSemaphore);
  1107. end;
  1108. if AThreadListLen > 1 then
  1109. begin
  1110. {$IFDEF DEBUG_MT}
  1111. SysDebugLn('FPC AThreads: All threads exited but some lacking cleanup - trying to free up resources...');
  1112. {$ENDIF}
  1113. p:=AThreadList;
  1114. while p <> nil do
  1115. begin
  1116. pn:=p^.nextThread;
  1117. if not p^.mainThread then
  1118. RemoveFromThreadList(AThreadList,p^.threadID);
  1119. p:=pn;
  1120. end;
  1121. end
  1122. else
  1123. begin
  1124. {$IFDEF DEBUG_MT}
  1125. SysDebugLn('FPC AThreads: All threads exited normally.');
  1126. {$ENDIF}
  1127. end;
  1128. ReleaseSemaphore(@AThreadListSemaphore);
  1129. end;
  1130. initialization
  1131. initsystemthreads;
  1132. {$IFDEF DEBUG_MT}
  1133. SysDebugLn('FPC AThreads: Unit Initialization');
  1134. {$ENDIF}
  1135. if ThreadingAlreadyUsed then
  1136. begin
  1137. writeln('Threading has been used before athreads was initialized.');
  1138. writeln('Make athreads one of the first units in your uses clause!');
  1139. runerror(211);
  1140. end;
  1141. AThreadList:=nil;
  1142. AThreadListLen:=0;
  1143. AThreadNum:=-1; { Mainthread will be 0. }
  1144. InitSemaphore(@AThreadListSemaphore);
  1145. SetAThreadManager;
  1146. {$IFDEF DEBUG_MT}
  1147. SysDebugLn('FPC AThreads: Unit Initialization Done');
  1148. {$ENDIF}
  1149. finalization
  1150. {$IFDEF DEBUG_MT}
  1151. SysDebugLn('FPC AThreads: Unit Finalization');
  1152. {$ENDIF}
  1153. WaitForAllThreads;
  1154. end.