cthreads.pp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086
  1. {
  2. This file is part of the Free Pascal run time library.
  3. Copyright (c) 2002 by Peter Vreman,
  4. member of the Free Pascal development team.
  5. pthreads threading support implementation
  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. {$ifdef linux}
  14. { we can combine both compile-time linking and dynamic loading, in order to:
  15. a) solve a problem on some systems with dynamically loading libpthread if
  16. it's not linked at compile time
  17. b) still enabling dynamically checking whether or not certain functions
  18. are available (could also be implemented via weak linking)
  19. }
  20. {$linklib pthread}
  21. {$define dynpthreads} // Useless on BSD, since they are in libc
  22. {$endif}
  23. { sem_init is best, since it does not consume any file descriptors. }
  24. { sem_open is second best, since it consumes only one file descriptor }
  25. { per semaphore. }
  26. { If neither is available, pipe is used as fallback, which consumes 2 }
  27. { file descriptors per semaphore. }
  28. { Darwin doesn't support nameless semaphores in at least }
  29. { Mac OS X 10.4.8/Darwin 8.8 }
  30. {$if not defined(darwin) and not defined(iphonesim)}
  31. {$define has_sem_init}
  32. {$define has_sem_getvalue}
  33. {$else }
  34. {$if defined(darwin) or defined(iphonesim)}
  35. {$define has_sem_open}
  36. {$endif}
  37. {$endif}
  38. {$if defined(linux) or defined(aix) or defined(android)}
  39. {$define has_sem_timedwait}
  40. {$endif}
  41. unit cthreads;
  42. interface
  43. {$S-}
  44. {$ifndef dynpthreads} // If you have problems compiling this on FreeBSD 5.x
  45. {$linklib c} // try adding -Xf
  46. {$if not defined(Darwin) and not defined(iphonesim) and not defined(Android)}
  47. {$ifndef haiku}
  48. {$linklib pthread}
  49. {$endif haiku}
  50. {$endif darwin}
  51. {$endif}
  52. {$if defined(Darwin) or defined(iphonesim)}
  53. {$define dynpthreads}
  54. {$endif darwin}
  55. {$define basicevents_with_pthread_cond}
  56. Procedure SetCThreadManager;
  57. implementation
  58. Uses
  59. {$if defined(Linux) and not defined(Android)}
  60. Linux,
  61. {$endif}
  62. BaseUnix,
  63. unix,
  64. unixtype,
  65. initc
  66. {$ifdef dynpthreads}
  67. ,dl
  68. {$endif}
  69. ;
  70. {*****************************************************************************
  71. System unit import
  72. *****************************************************************************}
  73. procedure fpc_threaderror; [external name 'FPC_THREADERROR'];
  74. {*****************************************************************************
  75. Generic overloaded
  76. *****************************************************************************}
  77. { Include OS specific parts. }
  78. {$i pthread.inc}
  79. Type PINTRTLEvent = ^TINTRTLEvent;
  80. TINTRTLEvent = record
  81. condvar: pthread_cond_t;
  82. mutex: pthread_mutex_t;
  83. isset: boolean;
  84. end;
  85. TTryWaitResult = (tw_error, tw_semwasunlocked, tw_semwaslocked);
  86. {*****************************************************************************
  87. Threadvar support
  88. *****************************************************************************}
  89. const
  90. threadvarblocksize : dword = 0;
  91. var
  92. TLSKey,
  93. CleanupKey : pthread_key_t;
  94. procedure CInitThreadvar(var offset : dword;size : dword);
  95. begin
  96. {$ifdef cpusparc}
  97. {$define threadvarblocksize_set}
  98. threadvarblocksize:=align(threadvarblocksize,16);
  99. {$endif cpusparc}
  100. {$ifdef cpusparc64}
  101. {$define threadvarblocksize_set}
  102. threadvarblocksize:=align(threadvarblocksize,16);
  103. {$endif cpusparc64}
  104. {$ifdef cpupowerpc}
  105. {$define threadvarblocksize_set}
  106. threadvarblocksize:=align(threadvarblocksize,8);
  107. {$endif cpupowerc}
  108. {$ifdef cpui386}
  109. {$define threadvarblocksize_set}
  110. threadvarblocksize:=align(threadvarblocksize,8);
  111. {$endif cpui386}
  112. {$ifdef cpuarm}
  113. {$define threadvarblocksize_set}
  114. threadvarblocksize:=align(threadvarblocksize,4);
  115. {$endif cpuarm}
  116. {$ifdef cpum68k}
  117. {$define threadvarblocksize_set}
  118. threadvarblocksize:=align(threadvarblocksize,2);
  119. {$endif cpum68k}
  120. {$ifdef cpux86_64}
  121. {$define threadvarblocksize_set}
  122. threadvarblocksize:=align(threadvarblocksize,16);
  123. {$endif cpux86_64}
  124. {$ifdef cpupowerpc64}
  125. {$define threadvarblocksize_set}
  126. threadvarblocksize:=align(threadvarblocksize,16);
  127. {$endif cpupowerpc64}
  128. {$ifdef cpuaarch64}
  129. {$define threadvarblocksize_set}
  130. threadvarblocksize:=align(threadvarblocksize,16);
  131. {$endif cpuaarch64}
  132. {$ifdef cpuriscv}
  133. {$define threadvarblocksize_set}
  134. threadvarblocksize:=align(threadvarblocksize,16);
  135. {$endif cpuriscv}
  136. {$ifdef cpumips}
  137. {$define threadvarblocksize_set}
  138. threadvarblocksize:=align(threadvarblocksize,16);
  139. {$endif cpumips}
  140. {$ifdef cpuxtensa}
  141. {$define threadvarblocksize_set}
  142. threadvarblocksize:=align(threadvarblocksize,16);
  143. {$endif cpuxtensa}
  144. {$ifdef cpuloongarch64}
  145. {$define threadvarblocksize_set}
  146. threadvarblocksize:=align(threadvarblocksize,16);
  147. {$endif cpuloongarch64}
  148. {$ifndef threadvarblocksize_set}
  149. {$error threadvarblocksize must be set! }
  150. {$endif threadvarblocksize_set}
  151. offset:=threadvarblocksize;
  152. inc(threadvarblocksize,size);
  153. end;
  154. procedure CAllocateThreadVars;
  155. var
  156. dataindex : pointer;
  157. begin
  158. {$ifndef FPC_SECTION_THREADVARS}
  159. { we've to allocate the memory from system }
  160. { because the FPC heap management uses }
  161. { exceptions which use threadvars but }
  162. { these aren't allocated yet ... }
  163. { allocate room on the heap for the thread vars }
  164. DataIndex:=Pointer(Fpmmap(nil,threadvarblocksize,3,MAP_PRIVATE+MAP_ANONYMOUS,-1,0));
  165. FillChar(DataIndex^,threadvarblocksize,0);
  166. pthread_setspecific(tlskey,dataindex);
  167. {$endif FPC_SECTION_THREADVARS}
  168. end;
  169. procedure CthreadCleanup(p: pointer); cdecl;
  170. {$ifdef DEBUG_MT}
  171. var
  172. s: string[100]; // not an ansistring
  173. {$endif DEBUG_MT}
  174. begin
  175. {$ifdef DEBUG_MT}
  176. s := 'finishing externally started thread'#10;
  177. fpwrite(0,s[1],length(s));
  178. {$endif DEBUG_MT}
  179. { Restore tlskey value as it may already have been set to null,
  180. in which case
  181. a) DoneThread can't release the memory
  182. b) accesses to threadvars from DoneThread or anything it
  183. calls would allocate new threadvar memory
  184. }
  185. pthread_setspecific(tlskey,p);
  186. { clean up }
  187. DoneThread;
  188. { the pthread routine that calls us is supposed to do this, but doesn't
  189. at least on Mac OS X 10.6 }
  190. pthread_setspecific(CleanupKey,nil);
  191. pthread_setspecific(tlskey,nil);
  192. end;
  193. procedure HookThread;
  194. begin
  195. { Allocate local thread vars, this must be the first thing,
  196. because the exception management and io depends on threadvars }
  197. CAllocateThreadVars;
  198. { we cannot know the stack size of the current thread, so pretend it
  199. is really large to prevent spurious stack overflow errors }
  200. InitThread(1000000000);
  201. { instruct the pthreads system to clean up this thread when it exits.
  202. Use current tlskey as value so that if tlskey is cleared before
  203. CleanupKey is called, we still know its value (the order in which
  204. pthread tls data is zeroed by pthreads is undefined, and under some
  205. systems the tlskey is cleared first) }
  206. pthread_setspecific(CleanupKey,pthread_getspecific(tlskey));
  207. end;
  208. function CRelocateThreadvar(offset : dword) : pointer;
  209. var
  210. P : Pointer;
  211. begin
  212. P:=pthread_getspecific(tlskey);
  213. { a thread which we did not create? }
  214. if (P=Nil) then
  215. begin
  216. HookThread;
  217. // If this also goes wrong: bye bye threadvars...
  218. P:=pthread_getspecific(tlskey);
  219. end;
  220. CRelocateThreadvar:=P+Offset;
  221. end;
  222. procedure CReleaseThreadVars;
  223. begin
  224. {$ifndef FPC_SECTION_THREADVARS}
  225. Fpmunmap(pointer(pthread_getspecific(tlskey)),threadvarblocksize);
  226. {$endif FPC_SECTION_THREADVARS}
  227. end;
  228. { Include OS independent Threadvar initialization }
  229. {*****************************************************************************
  230. Thread starting
  231. *****************************************************************************}
  232. type
  233. pthreadinfo = ^tthreadinfo;
  234. tthreadinfo = record
  235. f : tthreadfunc;
  236. p : pointer;
  237. stklen : cardinal;
  238. end;
  239. function ThreadMain(param : pointer) : pointer;cdecl;
  240. var
  241. ti : tthreadinfo;
  242. nset: tsigset;
  243. {$if defined(linux) and not defined(FPC_USE_LIBC)}
  244. nlibcset: tlibc_sigset;
  245. {$endif linux/no FPC_USE_LIBC}
  246. {$ifdef DEBUG_MT}
  247. // in here, don't use write/writeln before having called
  248. // InitThread! I wonder if anyone ever debugged these routines,
  249. // because they will have crashed if DEBUG_MT was enabled!
  250. // this took me the good part of an hour to figure out
  251. // why it was crashing all the time!
  252. // this is kind of a workaround, we simply write(2) to fd 0
  253. s: string[100]; // not an ansistring
  254. {$endif DEBUG_MT}
  255. begin
  256. {$ifdef DEBUG_MT}
  257. s := 'New thread started, initing threadvars'#10;
  258. fpwrite(0,s[1],length(s));
  259. {$endif DEBUG_MT}
  260. { unblock all signals we are interested in (may be blocked by }
  261. { default in new threads on some OSes, see #9073) }
  262. fpsigemptyset(nset);
  263. fpsigaddset(nset,SIGSEGV);
  264. fpsigaddset(nset,SIGBUS);
  265. fpsigaddset(nset,SIGFPE);
  266. fpsigaddset(nset,SIGILL);
  267. {$if defined(linux) and not defined(FPC_USE_LIBC)}
  268. { sigset_t has a different size for linux/kernel and linux/libc }
  269. fillchar(nlibcset,sizeof(nlibcset),0);
  270. if (sizeof(nlibcset)>sizeof(nset)) then
  271. move(nset,nlibcset,sizeof(nset))
  272. else
  273. move(nset,nlibcset,sizeof(nlibcset));
  274. pthread_sigmask(SIG_UNBLOCK,@nlibcset,nil);
  275. {$else linux}
  276. pthread_sigmask(SIG_UNBLOCK,@nset,nil);
  277. {$endif linux}
  278. { Allocate local thread vars, this must be the first thing,
  279. because the exception management and io depends on threadvars }
  280. CAllocateThreadVars;
  281. { Copy parameter to local data }
  282. {$ifdef DEBUG_MT}
  283. s := 'New thread started, initialising ...'#10;
  284. fpwrite(0,s[1],length(s));
  285. {$endif DEBUG_MT}
  286. ti:=pthreadinfo(param)^;
  287. { Initialize thread }
  288. InitThread(ti.stklen);
  289. dispose(pthreadinfo(param));
  290. { Start thread function }
  291. {$ifdef DEBUG_MT}
  292. writeln('Jumping to thread function');
  293. {$endif DEBUG_MT}
  294. ThreadMain:=pointer(ti.f(ti.p));
  295. DoneThread;
  296. pthread_exit(ThreadMain);
  297. end;
  298. var
  299. TLSInitialized : longbool = FALSE;
  300. Procedure InitCTLS;
  301. begin
  302. if (InterLockedExchange(longint(TLSInitialized),ord(true)) = 0) then
  303. begin
  304. { We're still running in single thread mode, setup the TLS }
  305. pthread_key_create(@TLSKey,nil);
  306. InitThreadVars(@CRelocateThreadvar);
  307. { used to clean up threads that we did not create ourselves:
  308. a) the default value for a key (and hence also this one) in
  309. new threads is NULL, and if it's still like that when the
  310. thread terminates, nothing will happen
  311. b) if it's non-NULL, the destructor routine will be called
  312. when the thread terminates
  313. -> we will set it to 1 if the threadvar relocation routine is
  314. called from a thread we did not create, so that we can
  315. clean up everything at the end }
  316. pthread_key_create(@CleanupKey,@CthreadCleanup);
  317. end
  318. end;
  319. function CBeginThread(sa : Pointer;stacksize : PtrUInt;
  320. ThreadFunction : tthreadfunc;p : pointer;
  321. creationFlags : dword; var ThreadId : TThreadId) : TThreadID;
  322. var
  323. ti : pthreadinfo;
  324. thread_attr : pthread_attr_t;
  325. begin
  326. {$ifdef DEBUG_MT}
  327. writeln('Creating new thread');
  328. {$endif DEBUG_MT}
  329. { Initialize multithreading if not done }
  330. if not TLSInitialized then
  331. InitCTLS;
  332. if not IsMultiThread then
  333. begin
  334. { We're still running in single thread mode, lazy initialize thread support }
  335. LazyInitThreading;
  336. IsMultiThread:=true;
  337. end;
  338. { the only way to pass data to the newly created thread
  339. in a MT safe way, is to use the heap }
  340. new(ti);
  341. ti^.f:=ThreadFunction;
  342. ti^.p:=p;
  343. ti^.stklen:=stacksize;
  344. { call pthread_create }
  345. {$ifdef DEBUG_MT}
  346. writeln('Starting new thread');
  347. {$endif DEBUG_MT}
  348. pthread_attr_init(@thread_attr);
  349. {$if not defined(HAIKU)and not defined(BEOS) and not defined(ANDROID)}
  350. {$if defined (solaris) or defined (netbsd) }
  351. pthread_attr_setinheritsched(@thread_attr, PTHREAD_INHERIT_SCHED);
  352. {$else not solaris}
  353. pthread_attr_setinheritsched(@thread_attr, PTHREAD_EXPLICIT_SCHED);
  354. {$endif not solaris}
  355. {$ifend}
  356. // will fail under linux -- apparently unimplemented
  357. pthread_attr_setscope(@thread_attr, PTHREAD_SCOPE_PROCESS);
  358. // don't create detached, we need to be able to join (waitfor) on
  359. // the newly created thread!
  360. //pthread_attr_setdetachstate(@thread_attr, PTHREAD_CREATE_DETACHED);
  361. // set the stack size
  362. if (pthread_attr_setstacksize(@thread_attr, stacksize)<>0) or
  363. // and create the thread
  364. (pthread_create(ppthread_t(@threadid), @thread_attr, @ThreadMain,ti) <> 0) then
  365. begin
  366. dispose(ti);
  367. threadid := TThreadID(0);
  368. end;
  369. CBeginThread:=threadid;
  370. pthread_attr_destroy(@thread_attr);
  371. {$ifdef DEBUG_MT}
  372. writeln('BeginThread returning ',ptrint(CBeginThread));
  373. {$endif DEBUG_MT}
  374. end;
  375. procedure CEndThread(ExitCode : DWord);
  376. begin
  377. DoneThread;
  378. pthread_detach(pthread_t(pthread_self()));
  379. pthread_exit(pointer(ptrint(ExitCode)));
  380. end;
  381. function CSuspendThread (threadHandle : TThreadID) : dword;
  382. begin
  383. { pthread_kill(SIGSTOP) cannot be used, because posix-compliant
  384. implementations then freeze the entire process instead of only
  385. the target thread. Suspending a particular thread is not
  386. supported by posix nor by most *nix implementations, presumably
  387. because of concerns mentioned in E.4 at
  388. http://pauillac.inria.fr/~xleroy/linuxthreads/faq.html#E and in
  389. http://java.sun.com/j2se/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html
  390. }
  391. // result := pthread_kill(threadHandle,SIGSTOP);
  392. result:=dword(-1);
  393. end;
  394. function CResumeThread (threadHandle : TThreadID) : dword;
  395. begin
  396. result:=dword(-1);
  397. end;
  398. procedure sched_yield; cdecl; external 'c' name 'sched_yield';
  399. procedure CThreadSwitch; {give time to other threads}
  400. begin
  401. { At least on Mac OS X, the pthread_yield_np calls through to this. }
  402. { Further, sched_yield is in POSIX and supported on FreeBSD 4+, }
  403. { Linux, Mac OS X and Solaris, while the thread-specific yield }
  404. { routines are called differently everywhere and non-standard. }
  405. sched_yield;
  406. end;
  407. function CKillThread (threadHandle : TThreadID) : dword;
  408. begin
  409. pthread_detach(pthread_t(threadHandle));
  410. {$ifndef android}
  411. CKillThread := pthread_cancel(pthread_t(threadHandle));
  412. {$else}
  413. CKillThread := dword(-1);
  414. {$endif}
  415. end;
  416. function CCloseThread (threadHandle : TThreadID) : dword;
  417. begin
  418. result:=0;
  419. end;
  420. function CWaitForThreadTerminate (threadHandle : TThreadID; TimeoutMs : longint) : dword; {0=no timeout}
  421. var
  422. LResultP: Pointer;
  423. begin
  424. pthread_join(pthread_t(threadHandle), @LResultP);
  425. CWaitForThreadTerminate := dword(LResultP);
  426. end;
  427. function CThreadSetPriority (threadHandle : TThreadID; Prio: longint): boolean; {-15..+15, 0=normal}
  428. begin
  429. {$Warning ThreadSetPriority needs to be implemented}
  430. result:=false;
  431. end;
  432. function CThreadGetPriority (threadHandle : TThreadID): Integer;
  433. begin
  434. {$Warning ThreadGetPriority needs to be implemented}
  435. result:=0;
  436. end;
  437. function CGetCurrentThreadId : TThreadID;
  438. begin
  439. CGetCurrentThreadId := TThreadID (pthread_self());
  440. end;
  441. procedure CSetThreadDebugNameA(threadHandle: TThreadID; const ThreadName: AnsiString);
  442. {$if defined(Linux) or defined(Android)}
  443. var
  444. CuttedName: AnsiString;
  445. {$endif}
  446. begin
  447. {$if defined(Linux) or defined(Android)}
  448. if ThreadName = '' then
  449. Exit;
  450. {$ifdef dynpthreads}
  451. if Assigned(pthread_setname_np) then
  452. {$endif dynpthreads}
  453. begin
  454. // length restricted to 16 characters including terminating null byte
  455. CuttedName:=Copy(ThreadName, 1, 15);
  456. if threadHandle=TThreadID(-1) then
  457. begin
  458. pthread_setname_np(pthread_self(), @CuttedName[1]);
  459. end
  460. else
  461. begin
  462. pthread_setname_np(pthread_t(threadHandle), @CuttedName[1]);
  463. end;
  464. end;
  465. {$elseif defined(Darwin) or defined(iphonesim)}
  466. {$ifdef dynpthreads}
  467. if Assigned(pthread_setname_np) then
  468. {$endif dynpthreads}
  469. begin
  470. // only allowed to set from within the thread
  471. if threadHandle=TThreadID(-1) then
  472. pthread_setname_np(@ThreadName[1]);
  473. end;
  474. {$else}
  475. {$Warning SetThreadDebugName needs to be implemented}
  476. {$endif}
  477. end;
  478. procedure CSetThreadDebugNameU(threadHandle: TThreadID; const ThreadName: UnicodeString);
  479. begin
  480. {$if defined(Linux) or defined(Android)}
  481. {$ifdef dynpthreads}
  482. if Assigned(pthread_setname_np) then
  483. {$endif dynpthreads}
  484. begin
  485. CSetThreadDebugNameA(threadHandle, AnsiString(ThreadName));
  486. end;
  487. {$elseif defined(Darwin) or defined(iphonesim)}
  488. {$ifdef dynpthreads}
  489. if Assigned(pthread_setname_np) then
  490. {$endif dynpthreads}
  491. begin
  492. CSetThreadDebugNameA(threadHandle, AnsiString(ThreadName));
  493. end;
  494. {$else}
  495. {$Warning SetThreadDebugName needs to be implemented}
  496. {$endif}
  497. end;
  498. {*****************************************************************************
  499. Delphi/Win32 compatibility
  500. *****************************************************************************}
  501. procedure CInitCriticalSection(var CS);
  502. var
  503. MAttr : pthread_mutexattr_t;
  504. res: longint;
  505. begin
  506. res:=pthread_mutexattr_init(@MAttr);
  507. if res=0 then
  508. begin
  509. res:=pthread_mutexattr_settype(@MAttr,longint(_PTHREAD_MUTEX_RECURSIVE));
  510. if res=0 then
  511. res := pthread_mutex_init(@CS,@MAttr)
  512. else
  513. { No recursive mutex support :/ }
  514. fpc_threaderror
  515. end
  516. else
  517. res:= pthread_mutex_init(@CS,NIL);
  518. pthread_mutexattr_destroy(@MAttr);
  519. if res <> 0 then
  520. fpc_threaderror;
  521. end;
  522. procedure CEnterCriticalSection(var CS);
  523. begin
  524. if pthread_mutex_lock(@CS) <> 0 then
  525. fpc_threaderror
  526. end;
  527. function CTryEnterCriticalSection(var CS):longint;
  528. begin
  529. if pthread_mutex_Trylock(@CS)=0 then
  530. result:=1 // succes
  531. else
  532. result:=0; // failure
  533. end;
  534. procedure CLeaveCriticalSection(var CS);
  535. begin
  536. if pthread_mutex_unlock(@CS) <> 0 then
  537. fpc_threaderror
  538. end;
  539. procedure CDoneCriticalSection(var CS);
  540. begin
  541. { unlock as long as unlocking works to unlock it if it is recursive
  542. some Delphi code might call this function with a locked mutex }
  543. while pthread_mutex_unlock(@CS)=0 do
  544. ;
  545. if pthread_mutex_destroy(@CS) <> 0 then
  546. fpc_threaderror;
  547. end;
  548. {*****************************************************************************
  549. Semaphore routines
  550. *****************************************************************************}
  551. type
  552. TPthreadCondition = pthread_cond_t;
  553. TPthreadMutex = pthread_mutex_t;
  554. Tbasiceventstate=record
  555. FCondVar: TPthreadCondition;
  556. {$if defined(Linux) and not defined(Android)}
  557. FAttr: pthread_condattr_t;
  558. FClockID: longint;
  559. {$ifend}
  560. FEventSection: TPthreadMutex;
  561. FWaiters: longint;
  562. FIsSet,
  563. FManualReset,
  564. FDestroying : Boolean;
  565. end;
  566. plocaleventstate = ^tbasiceventstate;
  567. // peventstate=pointer;
  568. Const
  569. wrSignaled = 0;
  570. wrTimeout = 1;
  571. wrAbandoned= 2;
  572. wrError = 3;
  573. function IntBasicEventCreate(EventAttributes : Pointer; AManualReset,InitialState : Boolean;const Name : ansistring):pEventState;
  574. var
  575. MAttr : pthread_mutexattr_t;
  576. res : cint;
  577. {$if defined(Linux) and not defined(Android)}
  578. timespec: ttimespec;
  579. {$ifend}
  580. begin
  581. new(plocaleventstate(result));
  582. plocaleventstate(result)^.FManualReset:=AManualReset;
  583. plocaleventstate(result)^.FWaiters:=0;
  584. plocaleventstate(result)^.FDestroying:=False;
  585. plocaleventstate(result)^.FIsSet:=InitialState;
  586. {$if defined(Linux) and not defined(Android)}
  587. res := pthread_condattr_init(@plocaleventstate(result)^.FAttr);
  588. if (res <> 0) then
  589. begin
  590. FreeMem(result);
  591. fpc_threaderror;
  592. end;
  593. if clock_gettime(CLOCK_MONOTONIC_RAW, @timespec) = 0 then
  594. begin
  595. res := pthread_condattr_setclock(@plocaleventstate(result)^.FAttr, CLOCK_MONOTONIC_RAW);
  596. end
  597. else
  598. begin
  599. res := -1; // No support for CLOCK_MONOTONIC_RAW
  600. end;
  601. if (res = 0) then
  602. begin
  603. plocaleventstate(result)^.FClockID := CLOCK_MONOTONIC_RAW;
  604. end
  605. else
  606. begin
  607. res := pthread_condattr_setclock(@plocaleventstate(result)^.FAttr, CLOCK_MONOTONIC);
  608. if (res = 0) then
  609. begin
  610. plocaleventstate(result)^.FClockID := CLOCK_MONOTONIC;
  611. end
  612. else
  613. begin
  614. pthread_condattr_destroy(@plocaleventstate(result)^.FAttr);
  615. FreeMem(result);
  616. fpc_threaderror;
  617. end;
  618. end;
  619. res := pthread_cond_init(@plocaleventstate(result)^.FCondVar, @plocaleventstate(result)^.FAttr);
  620. if (res <> 0) then
  621. begin
  622. pthread_condattr_destroy(@plocaleventstate(result)^.FAttr);
  623. FreeMem(result);
  624. fpc_threaderror;
  625. end;
  626. {$else}
  627. res := pthread_cond_init(@plocaleventstate(result)^.FCondVar, nil);
  628. if (res <> 0) then
  629. begin
  630. FreeMem(result);
  631. fpc_threaderror;
  632. end;
  633. {$ifend}
  634. res:=pthread_mutexattr_init(@MAttr);
  635. if res=0 then
  636. begin
  637. res:=pthread_mutexattr_settype(@MAttr,longint(_PTHREAD_MUTEX_RECURSIVE));
  638. if Res=0 then
  639. Res:=pthread_mutex_init(@plocaleventstate(result)^.feventsection,@MAttr)
  640. else
  641. res:=pthread_mutex_init(@plocaleventstate(result)^.feventsection,nil);
  642. end
  643. else
  644. res:=pthread_mutex_init(@plocaleventstate(result)^.feventsection,nil);
  645. pthread_mutexattr_destroy(@MAttr);
  646. if res <> 0 then
  647. begin
  648. pthread_cond_destroy(@plocaleventstate(result)^.FCondVar);
  649. {$if defined(Linux) and not defined(Android)}
  650. pthread_condattr_destroy(@plocaleventstate(result)^.FAttr);
  651. {$ifend}
  652. FreeMem(result);
  653. fpc_threaderror;
  654. end;
  655. end;
  656. procedure Intbasiceventdestroy(state:peventstate);
  657. begin
  658. { safely mark that we are destroying this event }
  659. pthread_mutex_lock(@plocaleventstate(state)^.feventsection);
  660. plocaleventstate(state)^.FDestroying:=true;
  661. { send a signal to all threads that are waiting }
  662. pthread_cond_broadcast(@plocaleventstate(state)^.FCondVar);
  663. pthread_mutex_unlock(@plocaleventstate(state)^.feventsection);
  664. { now wait until they've finished their business }
  665. while (plocaleventstate(state)^.FWaiters <> 0) do
  666. cThreadSwitch;
  667. { and clean up }
  668. pthread_cond_destroy(@plocaleventstate(state)^.Fcondvar);
  669. {$if defined(Linux) and not defined(Android)}
  670. pthread_condattr_destroy(@plocaleventstate(state)^.FAttr);
  671. {$ifend}
  672. pthread_mutex_destroy(@plocaleventstate(state)^.FEventSection);
  673. dispose(plocaleventstate(state));
  674. end;
  675. procedure IntbasiceventResetEvent(state:peventstate);
  676. begin
  677. pthread_mutex_lock(@plocaleventstate(state)^.feventsection);
  678. plocaleventstate(state)^.fisset:=false;
  679. pthread_mutex_unlock(@plocaleventstate(state)^.feventsection);
  680. end;
  681. procedure IntbasiceventSetEvent(state:peventstate);
  682. begin
  683. pthread_mutex_lock(@plocaleventstate(state)^.feventsection);
  684. plocaleventstate(state)^.Fisset:=true;
  685. if not(plocaleventstate(state)^.FManualReset) then
  686. pthread_cond_signal(@plocaleventstate(state)^.Fcondvar)
  687. else
  688. pthread_cond_broadcast(@plocaleventstate(state)^.Fcondvar);
  689. pthread_mutex_unlock(@plocaleventstate(state)^.feventsection);
  690. end;
  691. function IntbasiceventWaitFor(Timeout : Cardinal;state:peventstate;FUseComWait : Boolean=False) : longint;
  692. var
  693. timespec: ttimespec;
  694. errres: cint;
  695. isset: boolean;
  696. tnow : timeval;
  697. begin
  698. { safely check whether we are being destroyed, if so immediately return. }
  699. { otherwise (under the same mutex) increase the number of waiters }
  700. pthread_mutex_lock(@plocaleventstate(state)^.feventsection);
  701. if (plocaleventstate(state)^.FDestroying) then
  702. begin
  703. pthread_mutex_unlock(@plocaleventstate(state)^.feventsection);
  704. result := wrAbandoned;
  705. exit;
  706. end;
  707. { not a regular inc() because it may happen simulatneously with the }
  708. { interlockeddecrement() at the end }
  709. interlockedincrement(plocaleventstate(state)^.FWaiters);
  710. //Wait without timeout using pthread_cond_wait
  711. if Timeout = $FFFFFFFF then
  712. begin
  713. while (not plocaleventstate(state)^.FIsSet) and (not plocaleventstate(state)^.FDestroying) do
  714. pthread_cond_wait(@plocaleventstate(state)^.Fcondvar, @plocaleventstate(state)^.feventsection);
  715. end
  716. else
  717. begin
  718. //Wait with timeout using pthread_cond_timedwait
  719. {$if defined(Linux) and not defined(Android)}
  720. if clock_gettime(plocaleventstate(state)^.FClockID, @timespec) <> 0 then
  721. begin
  722. Result := Ord(wrError);
  723. Exit;
  724. end;
  725. timespec.tv_sec := timespec.tv_sec + (clong(timeout) div 1000);
  726. timespec.tv_nsec := ((clong(timeout) mod 1000) * 1000000) + (timespec.tv_nsec);
  727. {$else}
  728. // TODO: FIX-ME: Also use monotonic clock for other *nix targets
  729. fpgettimeofday(@tnow, nil);
  730. timespec.tv_sec := tnow.tv_sec + (clong(timeout) div 1000);
  731. timespec.tv_nsec := ((clong(timeout) mod 1000) * 1000000) + (tnow.tv_usec * 1000);
  732. {$ifend}
  733. if timespec.tv_nsec >= 1000000000 then
  734. begin
  735. inc(timespec.tv_sec);
  736. dec(timespec.tv_nsec, 1000000000);
  737. end;
  738. errres := 0;
  739. while (not plocaleventstate(state)^.FDestroying) and
  740. (not plocaleventstate(state)^.FIsSet) and
  741. (errres<>ESysETIMEDOUT) do
  742. errres := pthread_cond_timedwait(@plocaleventstate(state)^.Fcondvar,
  743. @plocaleventstate(state)^.feventsection,
  744. @timespec);
  745. end;
  746. isset := plocaleventstate(state)^.FIsSet;
  747. { if ManualReset=false, reset the event immediately. }
  748. if (plocaleventstate(state)^.FManualReset=false) then
  749. plocaleventstate(state)^.FIsSet := false;
  750. //check the results...
  751. if plocaleventstate(state)^.FDestroying then
  752. Result := wrAbandoned
  753. else
  754. if IsSet then
  755. Result := wrSignaled
  756. else
  757. begin
  758. if errres=ESysETIMEDOUT then
  759. Result := wrTimeout
  760. else
  761. Result := wrError;
  762. end;
  763. pthread_mutex_unlock(@plocaleventstate(state)^.feventsection);
  764. { don't put this above the previous pthread_mutex_unlock, because }
  765. { otherwise we can get errors in case an object is destroyed between }
  766. { end of the wait/sleep loop and the signalling above. }
  767. { The pthread_mutex_unlock above takes care of the memory barrier }
  768. interlockeddecrement(plocaleventstate(state)^.FWaiters);
  769. end;
  770. function intRTLEventCreate: PRTLEvent;
  771. var p:pintrtlevent;
  772. begin
  773. new(p);
  774. if not assigned(p) then
  775. fpc_threaderror;
  776. if pthread_cond_init(@p^.condvar, nil)<>0 then
  777. begin
  778. dispose(p);
  779. fpc_threaderror;
  780. end;
  781. if pthread_mutex_init(@p^.mutex, nil)<>0 then
  782. begin
  783. pthread_cond_destroy(@p^.condvar);
  784. dispose(p);
  785. fpc_threaderror;
  786. end;
  787. p^.isset:=false;
  788. result:=PRTLEVENT(p);
  789. end;
  790. procedure intRTLEventDestroy(AEvent: PRTLEvent);
  791. var p:pintrtlevent;
  792. begin
  793. p:=pintrtlevent(aevent);
  794. pthread_cond_destroy(@p^.condvar);
  795. pthread_mutex_destroy(@p^.mutex);
  796. dispose(p);
  797. end;
  798. procedure intRTLEventSetEvent(AEvent: PRTLEvent);
  799. var p:pintrtlevent;
  800. begin
  801. p:=pintrtlevent(aevent);
  802. pthread_mutex_lock(@p^.mutex);
  803. p^.isset:=true;
  804. pthread_cond_signal(@p^.condvar);
  805. pthread_mutex_unlock(@p^.mutex);
  806. end;
  807. procedure intRTLEventResetEvent(AEvent: PRTLEvent);
  808. var p:pintrtlevent;
  809. begin
  810. p:=pintrtlevent(aevent);
  811. pthread_mutex_lock(@p^.mutex);
  812. p^.isset:=false;
  813. pthread_mutex_unlock(@p^.mutex);
  814. end;
  815. procedure intRTLEventWaitFor(AEvent: PRTLEvent);
  816. var p:pintrtlevent;
  817. begin
  818. p:=pintrtlevent(aevent);
  819. pthread_mutex_lock(@p^.mutex);
  820. while not p^.isset do pthread_cond_wait(@p^.condvar, @p^.mutex);
  821. p^.isset:=false;
  822. pthread_mutex_unlock(@p^.mutex);
  823. end;
  824. procedure intRTLEventWaitForTimeout(AEvent: PRTLEvent;timeout : longint);
  825. var
  826. p : pintrtlevent;
  827. errres : cint;
  828. timespec : ttimespec;
  829. tnow : timeval;
  830. begin
  831. p:=pintrtlevent(aevent);
  832. fpgettimeofday(@tnow,nil);
  833. timespec.tv_sec:=tnow.tv_sec+(timeout div 1000);
  834. timespec.tv_nsec:=(timeout mod 1000)*1000000 + tnow.tv_usec*1000;
  835. if timespec.tv_nsec >= 1000000000 then
  836. begin
  837. inc(timespec.tv_sec);
  838. dec(timespec.tv_nsec, 1000000000);
  839. end;
  840. errres:=0;
  841. pthread_mutex_lock(@p^.mutex);
  842. while (not p^.isset) and
  843. (errres <> ESysETIMEDOUT) do
  844. begin
  845. errres:=pthread_cond_timedwait(@p^.condvar, @p^.mutex, @timespec);
  846. end;
  847. p^.isset:=false;
  848. pthread_mutex_unlock(@p^.mutex);
  849. end;
  850. type
  851. threadmethod = procedure of object;
  852. Function CInitThreads : Boolean;
  853. begin
  854. {$ifdef DEBUG_MT}
  855. Writeln('Entering InitThreads.');
  856. {$endif}
  857. {$ifndef dynpthreads}
  858. Result:=True;
  859. {$else}
  860. Result:=LoadPthreads;
  861. {$endif}
  862. ThreadID := TThreadID (pthread_self());
  863. {$ifdef DEBUG_MT}
  864. Writeln('InitThreads : ',Result);
  865. {$endif DEBUG_MT}
  866. // We assume that if you set the thread manager, the application is multithreading.
  867. InitCTLS;
  868. end;
  869. Function CDoneThreads : Boolean;
  870. begin
  871. {$ifndef dynpthreads}
  872. Result:=True;
  873. {$else}
  874. Result:=UnloadPthreads;
  875. {$endif}
  876. end;
  877. Var
  878. CThreadManager : TThreadManager;
  879. Procedure SetCThreadManager;
  880. begin
  881. With CThreadManager do begin
  882. InitManager :=@CInitThreads;
  883. DoneManager :=@CDoneThreads;
  884. BeginThread :=@CBeginThread;
  885. EndThread :=@CEndThread;
  886. SuspendThread :=@CSuspendThread;
  887. ResumeThread :=@CResumeThread;
  888. KillThread :=@CKillThread;
  889. ThreadSwitch :=@CThreadSwitch;
  890. CloseThread :=@CCloseThread;
  891. WaitForThreadTerminate :=@CWaitForThreadTerminate;
  892. ThreadSetPriority :=@CThreadSetPriority;
  893. ThreadGetPriority :=@CThreadGetPriority;
  894. GetCurrentThreadId :=@CGetCurrentThreadId;
  895. SetThreadDebugNameA :=@CSetThreadDebugNameA;
  896. SetThreadDebugNameU :=@CSetThreadDebugNameU;
  897. InitCriticalSection :=@CInitCriticalSection;
  898. DoneCriticalSection :=@CDoneCriticalSection;
  899. EnterCriticalSection :=@CEnterCriticalSection;
  900. TryEnterCriticalSection:=@CTryEnterCriticalSection;
  901. LeaveCriticalSection :=@CLeaveCriticalSection;
  902. InitThreadVar :=@CInitThreadVar;
  903. RelocateThreadVar :=@CRelocateThreadVar;
  904. AllocateThreadVars :=@CAllocateThreadVars;
  905. ReleaseThreadVars :=@CReleaseThreadVars;
  906. BasicEventCreate :=@intBasicEventCreate;
  907. BasicEventDestroy :=@intBasicEventDestroy;
  908. BasicEventResetEvent :=@intBasicEventResetEvent;
  909. BasicEventSetEvent :=@intBasicEventSetEvent;
  910. BasiceventWaitFor :=@intBasiceventWaitFor;
  911. rtlEventCreate :=@intrtlEventCreate;
  912. rtlEventDestroy :=@intrtlEventDestroy;
  913. rtlEventSetEvent :=@intrtlEventSetEvent;
  914. rtlEventResetEvent :=@intrtlEventResetEvent;
  915. rtleventWaitForTimeout :=@intrtleventWaitForTimeout;
  916. rtleventWaitFor :=@intrtleventWaitFor;
  917. end;
  918. SetThreadManager(CThreadManager);
  919. end;
  920. initialization
  921. if ThreadingAlreadyUsed then
  922. begin
  923. writeln('Threading has been used before cthreads was initialized.');
  924. writeln('Make cthreads one of the first units in your uses clause.');
  925. runerror(211);
  926. end;
  927. SetCThreadManager;
  928. finalization
  929. end.