cthreads.pp 31 KB

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