athreads.pp 37 KB

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