athreads.pp 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328
  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. Sem: TSignalSemaphore; // Semaphore to protect the whole stuff
  654. end;
  655. Function intRTLEventCreate: PRTLEvent;
  656. var p:pintrtlevent;
  657. begin
  658. new(p);
  659. p^.isset:=false;
  660. InitSemaphore(@p^.Sem);
  661. result:=PRTLEVENT(p);
  662. end;
  663. procedure intRTLEventDestroy(AEvent: PRTLEvent);
  664. var p:pintrtlevent;
  665. begin
  666. p:=pintrtlevent(aevent);
  667. dispose(p);
  668. end;
  669. procedure intRTLEventSetEvent(AEvent: PRTLEvent);
  670. var p:pintrtlevent;
  671. begin
  672. p:=pintrtlevent(aevent);
  673. ObtainSemaphore(@p^.Sem);
  674. p^.isset:=true;
  675. ReleaseSemaphore(@p^.Sem);
  676. end;
  677. procedure intRTLEventResetEvent(AEvent: PRTLEvent);
  678. var p:pintrtlevent;
  679. begin
  680. p:=pintrtlevent(aevent);
  681. ObtainSemaphore(@p^.Sem);
  682. p^.isset:=false;
  683. ReleaseSemaphore(@p^.Sem);
  684. end;
  685. procedure intRTLEventWaitFor(AEvent: PRTLEvent);
  686. var p:pintrtlevent;
  687. begin
  688. p:=pintrtlevent(aevent);
  689. ObtainSemaphore(@p^.Sem);
  690. while not p^.isset do
  691. begin
  692. ReleaseSemaphore(@p^.Sem);
  693. DOSDelay(1);
  694. ObtainSemaphore(@p^.Sem);
  695. end;
  696. p^.isset:=false;
  697. ReleaseSemaphore(@p^.Sem);
  698. end;
  699. procedure intRTLEventWaitForTimeout(AEvent: PRTLEvent;timeout : longint);
  700. var
  701. p : pintrtlevent;
  702. begin
  703. p:=pintrtlevent(aevent);
  704. timeout:=timeout div 20; // DOSDelay expects (1/50 seconds)
  705. ObtainSemaphore(@p^.Sem);
  706. while (not p^.isset) and (timeout > 0) do
  707. begin
  708. ReleaseSemaphore(@p^.Sem);
  709. DOSDelay(1);
  710. dec(timeout);
  711. ObtainSemaphore(@p^.Sem);
  712. end;
  713. p^.isset:=false;
  714. ReleaseSemaphore(@p^.Sem);
  715. end;
  716. procedure AInitCriticalSection(var CS);
  717. begin
  718. {$IFDEF DEBUG_MT}
  719. SysDebugLn('FPC AThreads: InitCriticalSection '+hexStr(@CS));
  720. {$ENDIF}
  721. InitSemaphore(PSignalSemaphore(@CS));
  722. end;
  723. procedure AEnterCriticalSection(var CS);
  724. begin
  725. {$IFDEF DEBUG_MT}
  726. SysDebugLn('FPC AThreads: EnterCriticalSection '+hexStr(@CS));
  727. {$ENDIF}
  728. ObtainSemaphore(PSignalSemaphore(@CS));
  729. end;
  730. function ATryEnterCriticalSection(var CS):longint;
  731. begin
  732. {$IFDEF DEBUG_MT}
  733. SysDebugLn('FPC AThreads: TryEnterCriticalSection '+hexStr(@CS));
  734. {$ENDIF}
  735. result:=DWord(AttemptSemaphore(PSignalSemaphore(@CS)));
  736. if result<>0 then
  737. result:=1;
  738. end;
  739. procedure ALeaveCriticalSection(var CS);
  740. begin
  741. {$IFDEF DEBUG_MT}
  742. SysDebugLn('FPC AThreads: LeaveCriticalSection '+hexStr(@CS));
  743. {$ENDIF}
  744. ReleaseSemaphore(PSignalSemaphore(@CS));
  745. end;
  746. procedure ADoneCriticalSection(var CS);
  747. begin
  748. {$IFDEF DEBUG_MT}
  749. SysDebugLn('FPC AThreads: DoneCriticalSection '+hexStr(@CS));
  750. {$ENDIF}
  751. { unlock as long as unlocking works to unlock it if it is recursive
  752. some Delphi code might call this function with a locked mutex }
  753. with TSignalSemaphore(CS) do
  754. while ss_NestCount > 0 do
  755. ReleaseSemaphore(PSignalSemaphore(@CS));
  756. end;
  757. // Event Stuff
  758. // Return values for WaitFor
  759. const
  760. wrSignaled = 0;
  761. wrTimeout = 1;
  762. wrAbandoned = 2;
  763. wrError = 3;
  764. // the internal AmigaEvent
  765. type
  766. TAmiEvent = record
  767. IsSet: Boolean; // the actual Event setting
  768. Manual: Boolean; // do not automatically reset the event
  769. Name: string; // Name for the event structure (needed for cross process)
  770. Waiter: Integer; // number of WaitFor waiting for this event
  771. Destroyed: Boolean; // the event is going to be destroyed, all WaitFor please leave first
  772. Sem: TSignalSemaphore; // Semaphore to protect the whole stuff
  773. end;
  774. PAmiEvent = ^TAmiEvent;
  775. // Create an Event
  776. function intBasicEventCreate(EventAttributes : Pointer;
  777. AManualReset,InitialState : Boolean;const Name : ansistring):pEventState;
  778. var
  779. AmiEvent: PAmiEvent;
  780. begin
  781. New(AmiEvent);
  782. AmiEvent^.isSet := InitialState;
  783. AmiEvent^.Name := Name;
  784. AmiEvent^.Waiter := 0;
  785. AmiEvent^.Manual := AManualReset;
  786. AmiEvent^.Destroyed := False;
  787. InitSemaphore(@AmiEvent^.Sem);
  788. Result := AmiEvent;
  789. end;
  790. procedure intbasiceventdestroy(state:peventstate);
  791. var
  792. AmiEvent: PAmiEvent absolute State;
  793. Waiter: Integer;
  794. begin
  795. if Assigned(AmiEvent) then
  796. begin
  797. ObtainSemaphore(@AmiEvent^.Sem);
  798. AmiEvent^.Destroyed := True; // we destroy the event
  799. ReleaseSemaphore(@AmiEvent^.Sem);
  800. repeat
  801. DosDelay(1);
  802. until AmiEvent^.Waiter <= 0;
  803. ObtainSemaphore(@AmiEvent^.Sem); // is there anyone still waiting for it?
  804. ReleaseSemaphore(@AmiEvent^.Sem);
  805. Dispose(AmiEvent);
  806. end;
  807. end;
  808. procedure intbasiceventResetEvent(state:peventstate);
  809. var
  810. AmiEvent: PAmiEvent absolute State;
  811. begin
  812. if Assigned(AmiEvent) then
  813. begin
  814. {$IFDEF DEBUG_AMIEVENT}
  815. SysDebugLn('AmiEvent: Reset Event');
  816. {$ENDIF}
  817. ObtainSemaphore(@AmiEvent^.Sem);
  818. AmiEvent^.IsSet := False;
  819. ReleaseSemaphore(@AmiEvent^.Sem);
  820. end;
  821. end;
  822. procedure intbasiceventSetEvent(state:peventstate);
  823. var
  824. AmiEvent: PAmiEvent absolute State;
  825. begin
  826. if Assigned(AmiEvent) then
  827. begin
  828. {$IFDEF DEBUG_AMIEVENT}
  829. SysDebugLn('AmiEvent: Set Event');
  830. {$ENDIF}
  831. ObtainSemaphore(@AmiEvent^.Sem);
  832. AmiEvent^.IsSet := True;
  833. ReleaseSemaphore(@AmiEvent^.Sem);
  834. end;
  835. end;
  836. // Timer stuff
  837. procedure NewList(List: PList); inline;
  838. begin
  839. with List^ do
  840. begin
  841. lh_Head := PNode(@lh_Tail);
  842. lh_Tail := nil;
  843. lh_TailPred := PNode(@lh_Head)
  844. end;
  845. end;
  846. function CreatePort(Name: PChar; Pri: LongInt): PMsgPort;
  847. var
  848. SigBit: ShortInt;
  849. Port: PMsgPort;
  850. begin
  851. Sigbit := AllocSignal(-1);
  852. if sigbit = -1 then
  853. CreatePort := nil;
  854. Port := ExecAllocMem(SizeOf(TMsgPort), MEMF_CLEAR);
  855. if Port = nil then
  856. begin
  857. FreeSignal(SigBit);
  858. CreatePort := nil;
  859. end;
  860. with port^ do
  861. begin
  862. if Assigned(Name) then
  863. mp_Node.ln_Name := Name
  864. else
  865. mp_Node.ln_Name := nil;
  866. mp_Node.ln_Pri := pri;
  867. mp_Node.ln_Type := 4;
  868. mp_Flags := 0;
  869. mp_SigBit := SigBit;
  870. mp_SigTask := FindTask(nil);
  871. end;
  872. if Assigned(Name) then
  873. AddPort(Port)
  874. else
  875. NewList(Addr(Port^.mp_MsgList));
  876. CreatePort := Port;
  877. end;
  878. procedure DeletePort(Port: PMsgPort);
  879. begin
  880. if port <> nil then
  881. begin
  882. if Port^.mp_Node.ln_Name <> nil then
  883. RemPort(Port);
  884. Port^.mp_Node.ln_Type := $FF;
  885. Port^.mp_MsgList.lh_Head := PNode(-1);
  886. FreeSignal(Port^.mp_SigBit);
  887. ExecFreeMem(Port, SizeOf(TMsgPort));
  888. end;
  889. end;
  890. function CreateExtIO(Port: PMsgPort; Size: LongInt): PIORequest;
  891. begin
  892. Result := nil;
  893. if Port <> nil then
  894. begin
  895. Result := ExecAllocMem(Size, MEMF_CLEAR);
  896. if Result <> nil then
  897. begin
  898. Result^.io_Message.mn_Node.ln_Type := 7;
  899. Result^.io_Message.mn_Length := Size;
  900. Result^.io_Message.mn_ReplyPort := Port;
  901. end;
  902. end;
  903. end;
  904. procedure DeleteExtIO (IoReq: PIORequest);
  905. begin
  906. if IoReq <> nil then
  907. begin
  908. IoReq^.io_Message.mn_Node.ln_Type := $FF;
  909. IoReq^.io_Message.mn_ReplyPort := PMsgPort(-1);
  910. IoReq^.io_Device := PDevice(-1);
  911. ExecFreeMem(IoReq, IoReq^.io_Message.mn_Length);
  912. end
  913. end;
  914. function Create_Timer(TheUnit: LongInt): PTimeRequest;
  915. var
  916. TimerPort: PMsgPort;
  917. begin
  918. Result := nil;
  919. TimerPort := CreatePort(nil, 0);
  920. if TimerPort = nil then
  921. Exit;
  922. Result := PTimeRequest(CreateExtIO(TimerPort, SizeOf(TTimeRequest)));
  923. if Result = Nil then
  924. begin
  925. DeletePort(TimerPort);
  926. Exit;
  927. end;
  928. if OpenDevice(TIMERNAME, TheUnit, PIORequest(Result), 0) <> 0 then
  929. begin
  930. DeleteExtIO(PIORequest(Result));
  931. DeletePort(TimerPort);
  932. Result := nil;
  933. end;
  934. end;
  935. Procedure Delete_Timer(WhichTimer: PTimeRequest);
  936. var
  937. WhichPort: PMsgPort;
  938. begin
  939. WhichPort := WhichTimer^.tr_Node.io_Message.mn_ReplyPort;
  940. if assigned(WhichTimer) then
  941. begin
  942. CloseDevice(PIORequest(WhichTimer));
  943. DeleteExtIO(PIORequest(WhichTimer));
  944. end;
  945. if Assigned(WhichPort) then
  946. DeletePort(WhichPort);
  947. end;
  948. function GetEventTime(TR: PTimeRequest): Int64;
  949. begin
  950. Result := -1;
  951. if tr = nil then
  952. Exit;
  953. tr^.tr_node.io_Command := TR_GETSYSTIME;
  954. DoIO(PIORequest(tr));
  955. // structure assignment
  956. Result := Int64(tr^.tr_time.TV_Secs) * 1000 + tr^.tr_time.TV_Micro div 1000;
  957. end;
  958. // End timer stuff
  959. // the mighty Waitfor routine
  960. function intbasiceventWaitFor(Timeout : Cardinal;state:peventstate) : longint;
  961. var
  962. AmiEvent: PAmiEvent absolute State;
  963. Tr: PTimeRequest = nil;
  964. StartTime, CurTime: Int64;
  965. begin
  966. {$IFDEF DEBUG_AMIEVENT}
  967. SysDebugLn('AmiEvent: Enter WaitFor');
  968. {$ENDIF}
  969. Result := wrError;
  970. if Assigned(AmiEvent) then
  971. begin
  972. // we do an initial Check
  973. ObtainSemaphore(@AmiEvent^.Sem);
  974. if AmiEvent^.Destroyed then
  975. begin
  976. Result := wrAbandoned; // we got destroyed, so we just leave
  977. {$IFDEF DEBUG_AMIEVENT}
  978. SysDebugLn('AmiEvent: WaitFor Early Destroy');
  979. {$ENDIF}
  980. Exit;
  981. end;
  982. if AmiEvent^.IsSet then
  983. begin
  984. Result := wrSignaled; // signal Already set
  985. if not AmiEvent^.Manual then
  986. AmiEvent^.IsSet := False;
  987. {$IFDEF DEBUG_AMIEVENT}
  988. SysDebugLn('AmiEvent: WaitFor Early Signaled');
  989. {$ENDIF}
  990. Exit;
  991. end;
  992. // signal not set, so we add this call to the waiterlist
  993. Inc(AmiEvent^.Waiter);
  994. ReleaseSemaphore(@AmiEvent^.Sem);
  995. // that means we have to wait and care about the timeout -> need a timer
  996. Tr := create_timer(UNIT_MICROHZ);
  997. if not Assigned(Tr) then // cannot create timer :-O
  998. Exit;
  999. // time we started the actual waiting
  1000. StartTime := GetEventTime(TR);
  1001. try
  1002. // the main loop, notice the breaks are inside the Obtain/Release
  1003. // therefore the finally block must release it, (and no other exit allowed!)
  1004. repeat
  1005. CurTime := GetEventTime(TR); // to check the timeout, outside obtain/release to save some time
  1006. ObtainSemaphore(@AmiEvent^.Sem);
  1007. // check the status of event
  1008. if AmiEvent^.Destroyed then
  1009. begin
  1010. Result := wrAbandoned; // we got destroyed
  1011. {$IFDEF DEBUG_AMIEVENT}
  1012. SysDebugLn('AmiEvent: WaitFor Destroy');
  1013. {$ENDIF}
  1014. break;
  1015. end;
  1016. if AmiEvent^.IsSet then
  1017. begin
  1018. Result := wrSignaled; // signal got set
  1019. {$IFDEF DEBUG_AMIEVENT}
  1020. SysDebugLn('AmiEvent: WaitFor Signaled');
  1021. {$ENDIF}
  1022. Break;
  1023. end;
  1024. if CurTime - StartTime > Timeout then
  1025. begin
  1026. Result := wrTimeOut; // we got a timeout
  1027. {$IFDEF DEBUG_AMIEVENT}
  1028. SysDebugLn('AmiEvent: WaitFor TimeOut');
  1029. {$ENDIF}
  1030. Break;
  1031. end;
  1032. // if we reach here, nothing happend...
  1033. // we release the semaphore and wait for other threads to do something
  1034. ReleaseSemaphore(@AmiEvent^.Sem);
  1035. DosDelay(1);
  1036. until False;
  1037. finally
  1038. // reset the Event if needed
  1039. if (Result = wrSignaled) and (not AmiEvent^.Manual) then
  1040. AmiEvent^.IsSet := False;
  1041. // we finished so get us away from waiter list
  1042. Dec(AmiEvent^.Waiter);
  1043. ReleaseSemaphore(@AmiEvent^.Sem); // unlock the event
  1044. Delete_timer(tr); // timer not needed anymore
  1045. end;
  1046. end;
  1047. {$IFDEF DEBUG_AMIEVENT}
  1048. SysDebugLn('AmiEvent: Leave WaitFor');
  1049. {$ENDIF}
  1050. end;
  1051. // end Event stuff
  1052. function AInitThreads : Boolean;
  1053. begin
  1054. {$ifdef DEBUG_MT}
  1055. SysDebugLn('FPC AThreads: Entering InitThreads...');
  1056. {$endif}
  1057. result:=true;
  1058. // We assume that if you set the thread manager, the application is multithreading.
  1059. InitAThreading;
  1060. ThreadID := TThreadID(GetCurrentThreadInfo);
  1061. end;
  1062. function ADoneThreads : Boolean;
  1063. begin
  1064. result:=true;
  1065. end;
  1066. procedure SetAThreadManager;
  1067. begin
  1068. with AThreadManager do begin
  1069. InitManager :=@AInitThreads;
  1070. DoneManager :=@ADoneThreads;
  1071. BeginThread :=@ABeginThread;
  1072. EndThread :=@AEndThread;
  1073. SuspendThread :=@ASuspendThread;
  1074. ResumeThread :=@AResumeThread;
  1075. KillThread :=@AKillThread;
  1076. ThreadSwitch :=@AThreadSwitch;
  1077. CloseThread :=@ACloseThread;
  1078. WaitForThreadTerminate :=@AWaitForThreadTerminate;
  1079. ThreadSetPriority :=@AThreadSetPriority;
  1080. ThreadGetPriority :=@AThreadGetPriority;
  1081. GetCurrentThreadId :=@AGetCurrentThreadId;
  1082. InitCriticalSection :=@AInitCriticalSection;
  1083. DoneCriticalSection :=@ADoneCriticalSection;
  1084. EnterCriticalSection :=@AEnterCriticalSection;
  1085. TryEnterCriticalSection:=@ATryEnterCriticalSection;
  1086. LeaveCriticalSection :=@ALeaveCriticalSection;
  1087. InitThreadVar :=@AInitThreadVar;
  1088. RelocateThreadVar :=@ARelocateThreadVar;
  1089. AllocateThreadVars :=@AAllocateThreadVars;
  1090. ReleaseThreadVars :=@AReleaseThreadVars;
  1091. BasicEventCreate :=@intBasicEventCreate;
  1092. BasicEventDestroy :=@intBasicEventDestroy;
  1093. BasicEventResetEvent :=@intBasicEventResetEvent;
  1094. BasicEventSetEvent :=@intBasicEventSetEvent;
  1095. BasiceventWaitFor :=@intBasicEventWaitFor;
  1096. rtlEventCreate :=@intrtlEventCreate;
  1097. rtlEventDestroy :=@intrtlEventDestroy;
  1098. rtlEventSetEvent :=@intrtlEventSetEvent;
  1099. rtlEventResetEvent :=@intrtlEventResetEvent;
  1100. rtleventWaitForTimeout :=@intrtleventWaitForTimeout;
  1101. rtleventWaitFor :=@intrtleventWaitFor;
  1102. end;
  1103. SetThreadManager(AThreadManager);
  1104. end;
  1105. Procedure InitSystemThreads; external name '_FPC_InitSystemThreads';
  1106. { This should only be called from the finalization }
  1107. procedure WaitForAllThreads;
  1108. var
  1109. p: PThreadInfo;
  1110. pn: PThreadInfo;
  1111. begin
  1112. { If we are the main thread exiting, we have to wait for our subprocesses to
  1113. exit. Because AmigaOS won't clean up for us. Also, after exiting the main
  1114. thread the OS unloads all the code segments with code potentially still
  1115. running in the background... So even waiting here forever is better than
  1116. exiting with active threads, which will most likely just kill the OS
  1117. immediately. (KB) }
  1118. ObtainSemaphore(@AThreadListSemaphore);
  1119. {$IFDEF DEBUG_MT}
  1120. if AThreadListLen > 1 then
  1121. begin
  1122. SysDebugLn('FPC AThreads: We have registered subthreads, checking their status...');
  1123. if CountRunningThreads(AThreadList) > 1 then
  1124. SysDebugLn('FPC AThreads: We have running subthreads, waiting for them to exit...');
  1125. end;
  1126. {$ENDIF}
  1127. while CountRunningThreads(AThreadList) > 1 do
  1128. begin
  1129. ReleaseSemaphore(@AThreadListSemaphore);
  1130. DOSDelay(1);
  1131. { Reobtain the semaphore... }
  1132. ObtainSemaphore(@AThreadListSemaphore);
  1133. end;
  1134. if AThreadListLen > 1 then
  1135. begin
  1136. {$IFDEF DEBUG_MT}
  1137. SysDebugLn('FPC AThreads: All threads exited but some lacking cleanup - trying to free up resources...');
  1138. {$ENDIF}
  1139. p:=AThreadList;
  1140. while p <> nil do
  1141. begin
  1142. pn:=p^.nextThread;
  1143. if not p^.mainThread then
  1144. RemoveFromThreadList(AThreadList,p^.threadID);
  1145. p:=pn;
  1146. end;
  1147. end
  1148. else
  1149. begin
  1150. {$IFDEF DEBUG_MT}
  1151. SysDebugLn('FPC AThreads: All threads exited normally.');
  1152. {$ENDIF}
  1153. end;
  1154. ReleaseSemaphore(@AThreadListSemaphore);
  1155. end;
  1156. initialization
  1157. initsystemthreads;
  1158. {$IFDEF DEBUG_MT}
  1159. SysDebugLn('FPC AThreads: Unit Initialization');
  1160. {$ENDIF}
  1161. if ThreadingAlreadyUsed then
  1162. begin
  1163. writeln('Threading has been used before athreads was initialized.');
  1164. writeln('Make athreads one of the first units in your uses clause!');
  1165. runerror(211);
  1166. end;
  1167. AThreadList:=nil;
  1168. AThreadListLen:=0;
  1169. AThreadNum:=-1; { Mainthread will be 0. }
  1170. InitSemaphore(@AThreadListSemaphore);
  1171. SetAThreadManager;
  1172. {$IFDEF DEBUG_MT}
  1173. SysDebugLn('FPC AThreads: Unit Initialization Done');
  1174. {$ENDIF}
  1175. finalization
  1176. {$IFDEF DEBUG_MT}
  1177. SysDebugLn('FPC AThreads: Unit Finalization');
  1178. {$ENDIF}
  1179. WaitForAllThreads;
  1180. end.