athreads.pp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969
  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. {$WARNING These should be in the system unit }
  16. { some BeginThread flags we support }
  17. const
  18. CREATE_SUSPENDED = 1;
  19. STACK_SIZE_PARAM_IS_A_RESERVATION = 2;
  20. procedure SetAThreadBaseName(s: String);
  21. implementation
  22. uses
  23. sysutils, exec, amigados, utility;
  24. const
  25. threadvarblocksize : dword = 0;
  26. var
  27. SubThreadBaseName: String = 'FPC Subthread';
  28. {.$define DEBUG_MT}
  29. type
  30. TThreadOperation = ( toNone, toStart, toResume, toExit );
  31. type
  32. PThreadMsg = ^TThreadMsg;
  33. PThreadInfo = ^TThreadInfo;
  34. TThreadInfo = record
  35. threadVars: Pointer; { have threadvars ptr as first field, so no offset is needed to access it (faster) }
  36. threadVarsSize: DWord; { size of the allocated threadvars block }
  37. nextThread: PThreadInfo; { threadinfos are a linked list, using this field }
  38. threadID: TThreadID; { thread ID, as returned by CreateNewProc() }
  39. stackLen: PtrUInt; { stack size the thread was construced with }
  40. exitCode: Pointer; { exitcode after the process has exited }
  41. f: TThreadFunc; { ThreadFunc function pointer }
  42. p: Pointer; { ThreadFunc argument }
  43. flags: dword; { Flags this thread were created with }
  44. num: longint; { This was the "num"th thread to created }
  45. mainthread: boolean; { true if this is our main thread }
  46. exited: boolean; { true if the thread has exited, and can be cleaned up }
  47. suspended: boolean; { true if the thread was started suspended, and not resumed yet }
  48. replyPort: PMsgPort; { Amiga exec.library IPC message reply port }
  49. replyMsg: PMessage; { exit message for the thread }
  50. name: String; { Thread's name }
  51. end;
  52. TThreadMsg = record
  53. tm_MsgNode : TMessage;
  54. tm_ThreadInfo: PThreadInfo;
  55. tm_Operation : TThreadOperation;
  56. end;
  57. var
  58. AThreadManager: TThreadManager;
  59. AThreadList: PThreadInfo;
  60. AThreadListLen: LongInt;
  61. AThreadNum: LongInt;
  62. AThreadListSemaphore: TSignalSemaphore;
  63. { Function to add a thread to the running threads list }
  64. procedure AddToThreadList(var l: PThreadInfo; ti: PThreadInfo);
  65. var
  66. p : PThreadInfo;
  67. inList: Boolean;
  68. begin
  69. inList:=False;
  70. ObtainSemaphore(@AThreadListSemaphore);
  71. if l = nil then
  72. { if the list is not yet allocated, the newly added
  73. threadinfo will be the first item }
  74. l:=ti
  75. else
  76. begin
  77. { otherwise, look for the last item and append }
  78. p:=l;
  79. while (p^.nextThread<>nil) do p:=p^.nextThread;
  80. p^.nextThread:=ti;
  81. end;
  82. inc(AThreadNum);
  83. ti^.num:=AThreadNum;
  84. inc(AThreadListLen);
  85. {$IFDEF DEBUG_MT}
  86. SysDebugLn('FPC AThreads: thread ID:'+hexstr(Pointer(ti^.threadID))+' added, now '+inttostr(AThreadListLen)+' thread(s) in list.');
  87. {$ENDIF}
  88. ReleaseSemaphore(@AThreadListSemaphore);
  89. end;
  90. { Function to remove a thread from running threads list }
  91. function RemoveFromThreadList(var l: PThreadInfo; threadID: TThreadID): boolean;
  92. var
  93. p : PThreadInfo;
  94. pprev : PThreadInfo;
  95. inList : Boolean;
  96. tmpNext: PThreadInfo;
  97. tmpInfo: PThreadInfo;
  98. begin
  99. inList:=False;
  100. if l=nil then
  101. begin
  102. RemoveFromThreadList:=inList;
  103. exit;
  104. end;
  105. ObtainSemaphore(@AThreadListSemaphore);
  106. p:=l;
  107. pprev:=nil;
  108. while (p <> nil) and (p^.threadID <> threadID) do
  109. begin
  110. pprev:=p;
  111. p:=p^.nextThread;
  112. end;
  113. if p <> nil then
  114. begin
  115. tmpNext:=p^.nextThread;
  116. if not p^.mainthread and p^.exited then
  117. begin
  118. {$IFDEF DEBUG_MT}
  119. SysDebugLn('FPC AThreads: Releasing resources for thread ID:'+hexStr(Pointer(threadID)));
  120. {$ENDIF}
  121. while GetMsg(p^.replyPort) <> nil do begin end;
  122. DeleteMsgPort(p^.replyPort);
  123. dispose(p^.replyMsg);
  124. {$ifdef DEBUG_MT}
  125. { When debug mode enabled, release the threadvars here, later, because the "normal" location }
  126. { is too early, because debug messages on the thread might still use the heap manager (KB) }
  127. {$ifdef AMIGA}
  128. ObtainSemaphore(ASYS_heapSemaphore);
  129. {$endif}
  130. FreePooled(ASYS_heapPool,p^.threadVars,p^.threadVarsSize);
  131. {$ifdef AMIGA}
  132. ReleaseSemaphore(ASYS_heapSemaphore);
  133. {$endif}
  134. {$endif}
  135. dispose(p);
  136. if pprev <> nil then
  137. pprev^.nextThread:=tmpNext;
  138. Dec(AThreadListLen);
  139. end
  140. else
  141. begin
  142. {$IFDEF DEBUG_MT}
  143. SysDebugLn('FPC AThreads: Error! Attempt to remove threadID, which is the mainthread or not exited:'+hexStr(Pointer(threadID)));
  144. {$ENDIF}
  145. inList:=false;
  146. end;
  147. end
  148. {$IFDEF DEBUG_MT}
  149. else
  150. SysDebugLn('FPC AThreads: Error! Attempt to remove threadID, which is not in list:'+hexStr(Pointer(threadID)))
  151. {$ENDIF}
  152. ;
  153. ReleaseSemaphore(@AThreadListSemaphore);
  154. RemoveFromThreadList:=inList;
  155. end;
  156. { Function to return a function's ThreadInfo based on the threadID }
  157. function GetThreadInfo(var l: PThreadInfo; threadID: TThreadID): PThreadInfo;
  158. var
  159. p : PThreadInfo;
  160. inList: Boolean;
  161. begin
  162. inList:=False;
  163. GetThreadInfo:=nil;
  164. if l = nil then
  165. exit;
  166. ObtainSemaphore(@AThreadListSemaphore);
  167. p:=l;
  168. while (p <> nil) and (p^.threadID <> threadID) do
  169. p:=p^.nextThread;
  170. GetThreadInfo:=p;
  171. ReleaseSemaphore(@AThreadListSemaphore);
  172. end;
  173. { Returns the number of threads still not exited in our threadlist }
  174. function CountRunningThreads(var l: PThreadInfo): LongInt;
  175. var
  176. p: PThreadInfo;
  177. begin
  178. CountRunningThreads:=0;
  179. ObtainSemaphore(@AThreadListSemaphore);
  180. p:=l;
  181. while p <> nil do
  182. begin
  183. inc(CountRunningThreads,ord(not p^.exited));
  184. p:=p^.nextThread;
  185. end;
  186. ReleaseSemaphore(@AThreadListSemaphore);
  187. end;
  188. { Helper function for IPC }
  189. procedure SendMessageToThread(var threadMsg: TThreadMsg; p: PThreadInfo; const op: TThreadOperation; waitReply: boolean);
  190. begin
  191. FillChar(threadMsg,sizeof(threadMsg),0);
  192. with threadMsg do
  193. begin
  194. with tm_MsgNode do
  195. begin
  196. mn_Node.ln_Type:=NT_MESSAGE;
  197. mn_Length:=SizeOf(TThreadMsg);
  198. if waitReply then
  199. mn_ReplyPort:=p^.replyPort
  200. else
  201. mn_ReplyPort:=nil;
  202. end;
  203. tm_ThreadInfo:=p;
  204. tm_Operation:=op;
  205. end;
  206. PutMsg(@PProcess(p^.threadID)^.pr_MsgPort,@threadMsg);
  207. if waitReply then
  208. begin
  209. WaitPort(p^.replyPort);
  210. GetMsg(p^.replyPort);
  211. end;
  212. end;
  213. procedure SetAThreadBaseName(s: String);
  214. begin
  215. ObtainSemaphore(@AThreadListSemaphore);
  216. SubThreadBaseName:=s;
  217. ReleaseSemaphore(@AThreadListSemaphore);
  218. end;
  219. function GetAThreadBaseName: String;
  220. begin
  221. ObtainSemaphore(@AThreadListSemaphore);
  222. GetAThreadBaseName:=SubThreadBaseName;
  223. ReleaseSemaphore(@AThreadListSemaphore);
  224. end;
  225. procedure AInitThreadvar(var offset : dword;size : dword);
  226. begin
  227. {$IFDEF DEBUG_MT}
  228. {SysDebugLn('FPC AThreads: InitThreadvar');}
  229. {$ENDIF}
  230. offset:=threadvarblocksize;
  231. inc(threadvarblocksize,size);
  232. end;
  233. function ARelocateThreadvar(offset : dword) : pointer;
  234. var
  235. p: PThreadInfo;
  236. begin
  237. {$IFDEF DEBUG_MT}
  238. {SysDebugLn('FPC AThreads: RelocateThreadvar');}
  239. {$ENDIF}
  240. p:=PThreadInfo(PProcess(FindTask(nil))^.pr_Task.tc_UserData);
  241. if (p <> nil) and (p^.threadVars <> nil) then
  242. result:=p^.threadVars + Offset
  243. else
  244. result:=nil;
  245. end;
  246. procedure AAllocateThreadVars;
  247. var
  248. p: PThreadInfo;
  249. begin
  250. {$ifdef DEBUG_MT}
  251. SysDebugLn('FPC AThreads: Allocating threadvars');
  252. {$endif}
  253. { we've to allocate the memory from system }
  254. { because the FPC heap management uses }
  255. { exceptions which use threadvars but }
  256. { these aren't allocated yet ... }
  257. { allocate room on the heap for the thread vars }
  258. p:=PThreadInfo(PProcess(FindTask(nil))^.pr_Task.tc_UserData);
  259. if p <> nil then
  260. begin
  261. {$ifdef AMIGA}
  262. ObtainSemaphore(ASYS_heapSemaphore);
  263. {$endif}
  264. p^.threadVars:=AllocPooled(ASYS_heapPool,threadvarblocksize);
  265. if p^.threadVars = nil then
  266. SysDebugLn('FPC AThreads: Failed to allocate threadvar memory!')
  267. else
  268. begin
  269. p^.threadVarsSize:=threadvarblocksize;
  270. FillChar(p^.threadVars^,threadvarblocksize,0);
  271. end;
  272. {$ifdef AMIGA}
  273. ReleaseSemaphore(ASYS_heapSemaphore);
  274. {$endif}
  275. end
  276. else
  277. begin
  278. {$ifdef DEBUG_MT}
  279. SysDebugLn('FPC AThreads: AllocateThreadVars: tc_UserData of this process was nil!')
  280. {$endif}
  281. end;
  282. end;
  283. procedure AReleaseThreadVars;
  284. var
  285. p: PThreadInfo;
  286. begin
  287. {$ifdef DEBUG_MT}
  288. SysDebugLn('FPC AThreads: Releasing threadvars');
  289. {$endif}
  290. p:=PThreadInfo(PProcess(FindTask(nil))^.pr_Task.tc_UserData);
  291. if (p <> nil) and (p^.threadVars <> nil) then
  292. begin
  293. {$ifndef DEBUG_MT}
  294. { When debug mode is enabled, do not release threadvars here, because }
  295. { Debug messages later might still need the heapmanager, which depends }
  296. { on the threadvar (KB) }
  297. {$ifdef AMIGA}
  298. ObtainSemaphore(ASYS_heapSemaphore);
  299. {$endif}
  300. FreePooled(ASYS_heapPool,p^.threadVars,p^.threadVarsSize);
  301. p^.threadVars:=nil;
  302. p^.threadVarsSize:=0;
  303. {$ifdef AMIGA}
  304. ReleaseSemaphore(ASYS_heapSemaphore);
  305. {$endif}
  306. {$endif DEBUG_MT}
  307. end
  308. else
  309. begin
  310. {$ifdef DEBUG_MT}
  311. SysDebugLn('FPC AThreads: ReleaseThreadVars: tc_UserData or threadVars area of this process was nil!')
  312. {$endif}
  313. end;
  314. end;
  315. procedure InitAThreading;
  316. var
  317. threadInfo: PThreadInfo;
  318. p: PProcess;
  319. begin
  320. if (InterLockedExchange(longint(IsMultiThread),ord(true)) = 0) then
  321. begin
  322. { We're still running in single thread mode, setup the TLS }
  323. {$ifdef DEBUG_MT}
  324. SysDebugLn('FPC AThreads: Entering multithreaded mode...');
  325. {$endif}
  326. p:=PProcess(FindTask(nil));
  327. new(threadInfo);
  328. FillChar(threadInfo^,sizeof(TThreadInfo),0);
  329. p^.pr_Task.tc_UserData:=threadInfo;
  330. threadInfo^.replyPort:=@p^.pr_MsgPort;
  331. threadInfo^.mainThread:=true;
  332. threadInfo^.threadID:=TThreadID(p);
  333. InitThreadVars(@ARelocateThreadvar);
  334. AddToThreadList(AThreadList,threadInfo);
  335. end;
  336. end;
  337. {$IFDEF DEBUG_MT}
  338. {$PUSH}
  339. { Because the string concat in SysDebugLn causes exception frames }
  340. {$IMPLICITEXCEPTIONS OFF}
  341. {$ENDIF}
  342. procedure ThreadFunc; cdecl;
  343. var
  344. thisThread: PProcess;
  345. threadMsg: PThreadMsg;
  346. resumeMsg: PThreadMsg;
  347. exitSuspend: boolean; // true if we have to exit instead of suspend
  348. threadInfo: PThreadInfo;
  349. begin
  350. thisThread:=PProcess(FindTask(nil));
  351. { wait for our start message to arrive, then fetch it }
  352. WaitPort(@thisThread^.pr_MsgPort);
  353. threadMsg:=PThreadMsg(GetMsg(@thisThread^.pr_MsgPort));
  354. { fetch existing threadinfo from the start message, and set
  355. it to tc_userData, so we can proceed with threadvars }
  356. threadInfo:=threadMsg^.tm_ThreadInfo;
  357. thisThread^.pr_Task.tc_userData:=threadInfo;
  358. { Allocate local thread vars, this must be the first thing,
  359. because the exception management and io depends on threadvars }
  360. AAllocateThreadVars;
  361. {$ifdef DEBUG_MT}
  362. { first debug line can't be before threadvar allocation }
  363. SysDebugLn('FPC AThreads: Entering subthread function, ID:'+hexStr(thisThread));
  364. {$endif}
  365. if threadInfo^.name <> '' then
  366. begin
  367. {$ifdef DEBUG_MT}
  368. { this line can't be before threadvar allocation }
  369. SysDebugLn('FPC AThreads: Renaming thread ID:'+hexStr(thisThread)+' to '+threadInfo^.name);
  370. {$endif}
  371. thisThread^.pr_Task.tc_Node.ln_Name:=PChar(@threadInfo^.name[1]);
  372. end;
  373. { Reply the message, so the calling thread could continue }
  374. { note that threadMsg was allocated on the caller's task, so }
  375. { it will be invalid below this point }
  376. ReplyMsg(PMessage(threadMsg));
  377. { if creating a suspended thread, wait for the wakeup message to arrive }
  378. { then check if we actually have to resume, or exit }
  379. exitSuspend:=false;
  380. if threadInfo^.suspended then
  381. begin
  382. {$ifdef DEBUG_MT}
  383. SysDebugLn('FPC AThreads: Suspending subthread on entry, ID:'+hexStr(thisThread));
  384. {$endif}
  385. WaitPort(@thisThread^.pr_MsgPort);
  386. resumeMsg:=PThreadMsg(GetMsg(@thisThread^.pr_MsgPort));
  387. exitSuspend:=resumeMsg^.tm_Operation <> toResume;
  388. threadInfo^.suspended:=false;
  389. ReplyMsg(PMessage(resumeMsg));
  390. {$ifdef DEBUG_MT}
  391. SysDebugLn('FPC AThreads: Resuming subthread on entry, ID:'+hexStr(thisThread)+', resumed only to exit: '+inttostr(ord(exitSuspend)));
  392. {$endif}
  393. end;
  394. { Finally, call the user code }
  395. if not exitSuspend then
  396. begin
  397. InitThread(threadInfo^.stackLen);
  398. threadInfo^.exitCode:=Pointer(threadInfo^.f(threadInfo^.p));
  399. DoneThread;
  400. end;
  401. {$ifdef DEBUG_MT}
  402. SysDebugLn('FPC AThreads: Exiting Subthread function, ID:'+hexStr(thisThread));
  403. {$endif}
  404. Forbid();
  405. threadInfo^.exited:=true;
  406. { Send our exit message... }
  407. with threadInfo^.replyMsg^ do
  408. begin
  409. mn_Node.ln_Type:=NT_MESSAGE;
  410. mn_Length:=SizeOf(TMessage);
  411. mn_ReplyPort:=nil;
  412. end;
  413. Forbid();
  414. threadInfo^.exited:=true;
  415. PutMsg(threadInfo^.replyPort,threadInfo^.replyMsg);
  416. end;
  417. {$IFDEF DEBUG_MT}
  418. {$POP} { reset implicitexceptions state }
  419. {$ENDIF}
  420. function CreateNewProc(Tags : Array Of PtrUInt) : PProcess;
  421. begin
  422. CreateNewProc:=CreateNewProcTagList(@Tags);
  423. end;
  424. function ABeginThread(sa : Pointer;stacksize : PtrUInt;
  425. ThreadFunction : tthreadfunc;p : pointer;
  426. creationFlags : dword; var ThreadId : TThreadId) : TThreadID;
  427. var
  428. threadInfo: PThreadInfo;
  429. threadMsg: TThreadMsg;
  430. threadName: String;
  431. replyPort: PMsgPort;
  432. subThread: PProcess;
  433. begin
  434. ABeginThread:=TThreadID(0);
  435. {$ifdef DEBUG_MT}
  436. SysDebugLn('FPC AThreads: Creating new thread...');
  437. {$endif DEBUG_MT}
  438. { Initialize multithreading if not done }
  439. if not IsMultiThread then
  440. InitAThreading;
  441. { the only way to pass data to the newly created thread
  442. in a MT safe way, is to use the heap }
  443. new(threadInfo);
  444. FillChar(threadInfo^,sizeof(TThreadInfo),0);
  445. threadInfo^.f:=ThreadFunction;
  446. threadInfo^.p:=p;
  447. if (creationFlags and STACK_SIZE_PARAM_IS_A_RESERVATION) > 0 then
  448. threadInfo^.stackLen:=stacksize
  449. else
  450. threadInfo^.stackLen:=System.StackLength; { inherit parent's stack size }
  451. threadInfo^.suspended:=(creationFlags and CREATE_SUSPENDED) > 0;
  452. {$ifdef DEBUG_MT}
  453. SysDebugLn('FPC AThreads: Starting new thread... Stack size: '+inttostr(threadInfo^.stackLen));
  454. {$endif}
  455. subThread:=CreateNewProc([
  456. {$IFDEF MORPHOS}
  457. NP_CodeType,CODETYPE_PPC,
  458. NP_PPCStackSize, threadInfo^.stacklen,
  459. {$ELSE}
  460. NP_StackSize, threadInfo^.stacklen,
  461. {$ENDIF}
  462. NP_Entry,PtrUInt(@ThreadFunc),
  463. TAG_DONE]);
  464. if subThread = nil then
  465. begin
  466. {$ifdef DEBUG_MT}
  467. SysDebugLn('FPC AThreads: Failed to start the subthread!');
  468. {$endif}
  469. exit;
  470. end;
  471. replyPort:=CreateMsgPort;
  472. ThreadID:=TThreadID(subThread);
  473. threadInfo^.threadID:=ThreadID;
  474. threadInfo^.replyPort:=replyPort;
  475. new(threadInfo^.replyMsg);
  476. // the thread should be started here, and waiting
  477. // for our start message, so send it
  478. {$ifdef DEBUG_MT}
  479. SysDebugLn('FPC AThreads: Sending start message to subthread and waiting for reply ID:'+hexStr(subThread));
  480. {$endif}
  481. AddToThreadList(AThreadList,threadInfo);
  482. { AddToThreadList assigned us a number, so use it to name the thread }
  483. threadInfo^.name:=GetAThreadBaseName+' #'+inttostr(threadInfo^.num);
  484. SendMessageToThread(threadMsg,threadInfo,toStart,true);
  485. ABeginThread:=ThreadId;
  486. {$ifdef DEBUG_MT}
  487. SysDebugLn('FPC AThreads: Thread created successfully, ID:'+hexStr(subThread));
  488. {$endif}
  489. end;
  490. procedure AEndThread(ExitCode : DWord);
  491. begin
  492. { Do not call DoneThread here. It will be called by the threadfunction, when it exits. }
  493. end;
  494. function ASuspendThread (threadHandle : TThreadID) : dword;
  495. begin
  496. {$ifdef DEBUG_MT}
  497. SysDebugLn('FPC AThreads: unsupported operation: SuspendThread called for ID:'+hexStr(Pointer(threadHandle)));
  498. {$endif}
  499. // cannot be properly supported on Amiga
  500. result:=dword(-1);
  501. end;
  502. function AResumeThread (threadHandle : TThreadID) : dword;
  503. var
  504. m: TThreadMsg;
  505. p: PThreadInfo;
  506. begin
  507. AResumeThread:=0;
  508. Forbid();
  509. p:=GetThreadInfo(AThreadList,threadHandle);
  510. if (p <> nil) and p^.suspended then
  511. begin
  512. {$ifdef DEBUG_MT}
  513. SysDebugLn('FPC AThreads: Waiting for thread to resume, ID:'+hexStr(Pointer(threadHandle)));
  514. {$endif}
  515. { WaitPort in SendMessageToThread will break the Forbid() state... }
  516. SendMessageToThread(m,p,toResume,true);
  517. AResumeThread:=0;
  518. end
  519. else
  520. begin
  521. {$ifdef DEBUG_MT}
  522. SysDebugLn('FPC AThreads: Error, attempt to resume a non-suspended thread, or invalid thread ID:'+hexStr(Pointer(threadHandle)));
  523. {$endif}
  524. AResumeThread:=dword(-1);
  525. end;
  526. Permit();
  527. end;
  528. procedure AThreadSwitch; {give time to other threads}
  529. begin
  530. { On Unix, this calls sched_yield();
  531. Harry 'Piru' Sintonen recommended to emulate this on Amiga systems with
  532. exec/Forbid-exec/Permit pair which is pretty fast to execute and will
  533. trigger a rescheduling.
  534. Another idea by Frank Mariak was to use exec/SetTaskPri() with the same
  535. priority }
  536. Forbid();
  537. Permit();
  538. end;
  539. function AKillThread (threadHandle : TThreadID) : dword;
  540. begin
  541. {$ifdef DEBUG_MT}
  542. SysDebugLn('FPC AThreads: unsupported operation: KillThread called for ID:'+hexStr(Pointer(threadHandle)));
  543. {$endif}
  544. // cannot be properly supported on Amiga
  545. AKillThread:=dword(-1);
  546. end;
  547. function ACloseThread (threadHandle : TThreadID) : dword;
  548. begin
  549. {$WARNING The return value here seems to be undocumented}
  550. RemoveFromThreadList(AThreadList, threadHandle);
  551. result:=0;
  552. end;
  553. function AWaitForThreadTerminate (threadHandle : TThreadID; TimeoutMs : longint) : dword; {0=no timeout}
  554. var
  555. p: PThreadInfo;
  556. m: TThreadMsg;
  557. begin
  558. {.$WARNING Support for timeout argument is not implemented}
  559. { But since CThreads uses pthread_join, which has also no timeout,
  560. I don't think this is a big issue. (KB) }
  561. AWaitForThreadTerminate:=0;
  562. Forbid();
  563. p:=GetThreadInfo(AThreadList,threadHandle);
  564. if (p <> nil) then
  565. begin
  566. if not p^.exited then
  567. begin
  568. {$ifdef DEBUG_MT}
  569. SysDebugLn('FPC AThreads: Waiting for thread to exit, ID:'+hexStr(Pointer(threadHandle)));
  570. {$endif}
  571. { WaitPort in SendMessageToThread will break the Forbid() state... }
  572. if p^.suspended then
  573. begin
  574. SendMessageToThread(m,p,toExit,true);
  575. {$ifdef DEBUG_MT}
  576. SysDebugLn('FPC AThreads: Signaled suspended thread to exit, ID:'+hexStr(Pointer(threadHandle)));
  577. {$endif}
  578. end;
  579. { WaitPort will break the Forbid() state... }
  580. WaitPort(p^.replyPort);
  581. GetMsg(p^.replyPort);
  582. end
  583. else
  584. {$ifdef DEBUG_MT}
  585. SysDebugLn('FPC AThreads: Thread already exited, ID:'+hexStr(Pointer(threadHandle)));
  586. {$endif}
  587. AWaitForThreadTerminate:=DWord(p^.exitCode);
  588. end
  589. else
  590. begin
  591. {$ifdef DEBUG_MT}
  592. SysDebugLn('FPC AThreads: Error, attempt to wait for invalid thread ID to exit, ID:'+hexStr(Pointer(threadHandle)));
  593. {$endif}
  594. AWaitForThreadTerminate:=dword(-1); { Return non-zero code on error. }
  595. end;
  596. Permit();
  597. end;
  598. function AThreadSetPriority (threadHandle : TThreadID; Prio: longint): boolean; {-15..+15, 0=normal}
  599. begin
  600. {$Warning ThreadSetPriority needs to be implemented}
  601. result:=false;
  602. end;
  603. function AThreadGetPriority (threadHandle : TThreadID): Integer;
  604. begin
  605. {$Warning ThreadGetPriority needs to be implemented}
  606. result:=0;
  607. end;
  608. function AGetCurrentThreadId : TThreadID;
  609. begin
  610. AGetCurrentThreadId := TThreadID(FindTask(nil));
  611. end;
  612. Type PINTRTLEvent = ^TINTRTLEvent;
  613. TINTRTLEvent = record
  614. isset: boolean;
  615. end;
  616. Function intRTLEventCreate: PRTLEvent;
  617. var p:pintrtlevent;
  618. begin
  619. new(p);
  620. result:=PRTLEVENT(p);
  621. end;
  622. procedure intRTLEventDestroy(AEvent: PRTLEvent);
  623. var p:pintrtlevent;
  624. begin
  625. p:=pintrtlevent(aevent);
  626. dispose(p);
  627. end;
  628. procedure intRTLEventSetEvent(AEvent: PRTLEvent);
  629. var p:pintrtlevent;
  630. begin
  631. p:=pintrtlevent(aevent);
  632. p^.isset:=true;
  633. end;
  634. procedure intRTLEventResetEvent(AEvent: PRTLEvent);
  635. var p:pintrtlevent;
  636. begin
  637. p:=pintrtlevent(aevent);
  638. p^.isset:=false;
  639. end;
  640. procedure intRTLEventWaitFor(AEvent: PRTLEvent);
  641. var p:pintrtlevent;
  642. begin
  643. p:=pintrtlevent(aevent);
  644. p^.isset:=false;
  645. end;
  646. procedure intRTLEventWaitForTimeout(AEvent: PRTLEvent;timeout : longint);
  647. var
  648. p : pintrtlevent;
  649. begin
  650. p:=pintrtlevent(aevent);
  651. end;
  652. procedure AInitCriticalSection(var CS);
  653. begin
  654. {$IFDEF DEBUG_MT}
  655. SysDebugLn('FPC AThreads: InitCriticalSection '+hexStr(@CS));
  656. {$ENDIF}
  657. InitSemaphore(PSignalSemaphore(@CS));
  658. end;
  659. procedure AEnterCriticalSection(var CS);
  660. begin
  661. {$IFDEF DEBUG_MT}
  662. SysDebugLn('FPC AThreads: EnterCriticalSection '+hexStr(@CS));
  663. {$ENDIF}
  664. ObtainSemaphore(PSignalSemaphore(@CS));
  665. end;
  666. function ATryEnterCriticalSection(var CS):longint;
  667. begin
  668. {$IFDEF DEBUG_MT}
  669. SysDebugLn('FPC AThreads: TryEnterCriticalSection '+hexStr(@CS));
  670. {$ENDIF}
  671. result:=DWord(AttemptSemaphore(PSignalSemaphore(@CS)));
  672. if result<>0 then
  673. result:=1;
  674. end;
  675. procedure ALeaveCriticalSection(var CS);
  676. begin
  677. {$IFDEF DEBUG_MT}
  678. SysDebugLn('FPC AThreads: LeaveCriticalSection '+hexStr(@CS));
  679. {$ENDIF}
  680. ReleaseSemaphore(PSignalSemaphore(@CS));
  681. end;
  682. procedure ADoneCriticalSection(var CS);
  683. begin
  684. {$IFDEF DEBUG_MT}
  685. SysDebugLn('FPC AThreads: DoneCriticalSection '+hexStr(@CS));
  686. {$ENDIF}
  687. { unlock as long as unlocking works to unlock it if it is recursive
  688. some Delphi code might call this function with a locked mutex }
  689. with TSignalSemaphore(CS) do
  690. while ss_NestCount > 0 do
  691. ReleaseSemaphore(PSignalSemaphore(@CS));
  692. end;
  693. function intBasicEventCreate(EventAttributes : Pointer;
  694. AManualReset,InitialState : Boolean;const Name : ansistring):pEventState;
  695. begin
  696. end;
  697. procedure intbasiceventdestroy(state:peventstate);
  698. begin
  699. end;
  700. procedure intbasiceventResetEvent(state:peventstate);
  701. begin
  702. end;
  703. procedure intbasiceventSetEvent(state:peventstate);
  704. begin
  705. end;
  706. function intbasiceventWaitFor(Timeout : Cardinal;state:peventstate) : longint;
  707. begin
  708. end;
  709. function ASemaphoreInit: Pointer;
  710. begin
  711. result:=nil;
  712. end;
  713. procedure ASemaphoreDestroy(const FSem: Pointer);
  714. begin
  715. end;
  716. procedure ASemaphoreWait(const FSem: Pointer);
  717. begin
  718. end;
  719. procedure ASemaphorePost(const FSem: Pointer);
  720. begin
  721. end;
  722. function AInitThreads : Boolean;
  723. begin
  724. {$ifdef DEBUG_MT}
  725. SysDebugLn('FPC AThreads: Entering InitThreads...');
  726. {$endif}
  727. result:=true;
  728. ThreadID := TThreadID(FindTask(nil));
  729. {$ifdef DEBUG_MT}
  730. {$endif DEBUG_MT}
  731. // We assume that if you set the thread manager, the application is multithreading.
  732. InitAThreading;
  733. end;
  734. function ADoneThreads : Boolean;
  735. begin
  736. result:=true;
  737. end;
  738. procedure SetAThreadManager;
  739. begin
  740. with AThreadManager do begin
  741. InitManager :=@AInitThreads;
  742. DoneManager :=@ADoneThreads;
  743. BeginThread :=@ABeginThread;
  744. EndThread :=@AEndThread;
  745. SuspendThread :=@ASuspendThread;
  746. ResumeThread :=@AResumeThread;
  747. KillThread :=@AKillThread;
  748. ThreadSwitch :=@AThreadSwitch;
  749. CloseThread :=@ACloseThread;
  750. WaitForThreadTerminate :=@AWaitForThreadTerminate;
  751. ThreadSetPriority :=@AThreadSetPriority;
  752. ThreadGetPriority :=@AThreadGetPriority;
  753. GetCurrentThreadId :=@AGetCurrentThreadId;
  754. InitCriticalSection :=@AInitCriticalSection;
  755. DoneCriticalSection :=@ADoneCriticalSection;
  756. EnterCriticalSection :=@AEnterCriticalSection;
  757. TryEnterCriticalSection:=@ATryEnterCriticalSection;
  758. LeaveCriticalSection :=@ALeaveCriticalSection;
  759. InitThreadVar :=@AInitThreadVar;
  760. RelocateThreadVar :=@ARelocateThreadVar;
  761. AllocateThreadVars :=@AAllocateThreadVars;
  762. ReleaseThreadVars :=@AReleaseThreadVars;
  763. BasicEventCreate :=@intBasicEventCreate;
  764. BasicEventDestroy :=@intBasicEventDestroy;
  765. BasicEventResetEvent :=@intBasicEventResetEvent;
  766. BasicEventSetEvent :=@intBasicEventSetEvent;
  767. BasiceventWaitFor :=@intBasicEventWaitFor;
  768. rtlEventCreate :=@intrtlEventCreate;
  769. rtlEventDestroy :=@intrtlEventDestroy;
  770. rtlEventSetEvent :=@intrtlEventSetEvent;
  771. rtlEventResetEvent :=@intrtlEventResetEvent;
  772. rtleventWaitForTimeout :=@intrtleventWaitForTimeout;
  773. rtleventWaitFor :=@intrtleventWaitFor;
  774. // semaphores
  775. SemaphoreInit :=@ASemaphoreInit;
  776. SemaphoreDestroy :=@ASemaphoreDestroy;
  777. SemaphoreWait :=@ASemaphoreWait;
  778. SemaphorePost :=@ASemaphorePost;
  779. end;
  780. SetThreadManager(AThreadManager);
  781. end;
  782. Procedure InitSystemThreads; external name '_FPC_InitSystemThreads';
  783. { This should only be called from the finalization }
  784. procedure WaitForAllThreads;
  785. begin
  786. { If we are the main thread exiting, we have to wait for our subprocesses to
  787. exit. Because AmigaOS won't clean up for us. Also, after exiting the main
  788. thread the OS unloads all the code segments with code potentially still
  789. running in the background... So even waiting here forever is better than
  790. exiting with active threads, which will most likely just kill the OS
  791. immediately. (KB) }
  792. ObtainSemaphore(@AThreadListSemaphore);
  793. {$IFDEF DEBUG_MT}
  794. if AThreadListLen > 1 then
  795. begin
  796. SysDebugLn('FPC AThreads: We have registered subthreads, checking their status...');
  797. if CountRunningThreads(AThreadList) > 1 then
  798. SysDebugLn('FPC AThreads: We have running subthreads, waiting for them to exit...');
  799. end;
  800. {$ENDIF}
  801. while CountRunningThreads(AThreadList) > 1 do
  802. begin
  803. ReleaseSemaphore(@AThreadListSemaphore);
  804. DOSDelay(1);
  805. { Reobtain the semaphore... }
  806. ObtainSemaphore(@AThreadListSemaphore);
  807. end;
  808. {$IFDEF DEBUG_MT}
  809. if AThreadListLen > 1 then
  810. SysDebugLn('FPC AThreads: All threads exited but some lacking cleanup - resources will be leaked!')
  811. else
  812. SysDebugLn('FPC AThreads: All threads exited normally.');
  813. {$ENDIF}
  814. ReleaseSemaphore(@AThreadListSemaphore);
  815. end;
  816. initialization
  817. initsystemthreads;
  818. {$IFDEF DEBUG_MT}
  819. SysDebugLn('FPC AThreads: Unit Initialization');
  820. {$ENDIF}
  821. if ThreadingAlreadyUsed then
  822. begin
  823. writeln('Threading has been used before athreads was initialized.');
  824. writeln('Make athreads one of the first units in your uses clause!');
  825. runerror(211);
  826. end;
  827. AThreadList:=nil;
  828. AThreadListLen:=0;
  829. AThreadNum:=-1; { Mainthread will be 0. }
  830. InitSemaphore(@AThreadListSemaphore);
  831. SetAThreadManager;
  832. finalization
  833. {$IFDEF DEBUG_MT}
  834. SysDebugLn('FPC AThreads: Unit Finalization');
  835. {$ENDIF}
  836. WaitForAllThreads;
  837. end.