cthreads.pp 32 KB

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