cthreads.pp 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  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. IsMultiThread:=true;
  298. { the only way to pass data to the newly created thread
  299. in a MT safe way, is to use the heap }
  300. new(ti);
  301. ti^.f:=ThreadFunction;
  302. ti^.p:=p;
  303. ti^.stklen:=stacksize;
  304. { call pthread_create }
  305. {$ifdef DEBUG_MT}
  306. writeln('Starting new thread');
  307. {$endif DEBUG_MT}
  308. pthread_attr_init(@thread_attr);
  309. {$if not defined(HAIKU)and not defined(BEOS) and not defined(ANDROID)}
  310. {$if defined (solaris) or defined (netbsd) }
  311. pthread_attr_setinheritsched(@thread_attr, PTHREAD_INHERIT_SCHED);
  312. {$else not solaris}
  313. pthread_attr_setinheritsched(@thread_attr, PTHREAD_EXPLICIT_SCHED);
  314. {$endif not solaris}
  315. {$ifend}
  316. // will fail under linux -- apparently unimplemented
  317. pthread_attr_setscope(@thread_attr, PTHREAD_SCOPE_PROCESS);
  318. // don't create detached, we need to be able to join (waitfor) on
  319. // the newly created thread!
  320. //pthread_attr_setdetachstate(@thread_attr, PTHREAD_CREATE_DETACHED);
  321. // set the stack size
  322. if (pthread_attr_setstacksize(@thread_attr, stacksize)<>0) or
  323. // and create the thread
  324. (pthread_create(ppthread_t(@threadid), @thread_attr, @ThreadMain,ti) <> 0) then
  325. begin
  326. dispose(ti);
  327. threadid := TThreadID(0);
  328. end;
  329. CBeginThread:=threadid;
  330. pthread_attr_destroy(@thread_attr);
  331. {$ifdef DEBUG_MT}
  332. writeln('BeginThread returning ',ptrint(CBeginThread));
  333. {$endif DEBUG_MT}
  334. end;
  335. procedure CEndThread(ExitCode : DWord);
  336. begin
  337. DoneThread;
  338. pthread_detach(pthread_t(pthread_self()));
  339. pthread_exit(pointer(ptrint(ExitCode)));
  340. end;
  341. function CSuspendThread (threadHandle : TThreadID) : dword;
  342. begin
  343. { pthread_kill(SIGSTOP) cannot be used, because posix-compliant
  344. implementations then freeze the entire process instead of only
  345. the target thread. Suspending a particular thread is not
  346. supported by posix nor by most *nix implementations, presumably
  347. because of concerns mentioned in E.4 at
  348. http://pauillac.inria.fr/~xleroy/linuxthreads/faq.html#E and in
  349. http://java.sun.com/j2se/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html
  350. }
  351. // result := pthread_kill(threadHandle,SIGSTOP);
  352. result:=dword(-1);
  353. end;
  354. function CResumeThread (threadHandle : TThreadID) : dword;
  355. begin
  356. result:=dword(-1);
  357. end;
  358. procedure sched_yield; cdecl; external 'c' name 'sched_yield';
  359. procedure CThreadSwitch; {give time to other threads}
  360. begin
  361. { At least on Mac OS X, the pthread_yield_np calls through to this. }
  362. { Further, sched_yield is in POSIX and supported on FreeBSD 4+, }
  363. { Linux, Mac OS X and Solaris, while the thread-specific yield }
  364. { routines are called differently everywhere and non-standard. }
  365. sched_yield;
  366. end;
  367. function CKillThread (threadHandle : TThreadID) : dword;
  368. begin
  369. pthread_detach(pthread_t(threadHandle));
  370. {$ifndef android}
  371. CKillThread := pthread_cancel(pthread_t(threadHandle));
  372. {$else}
  373. CKillThread := dword(-1);
  374. {$endif}
  375. end;
  376. function CCloseThread (threadHandle : TThreadID) : dword;
  377. begin
  378. result:=0;
  379. end;
  380. function CWaitForThreadTerminate (threadHandle : TThreadID; TimeoutMs : longint) : dword; {0=no timeout}
  381. var
  382. LResultP: Pointer;
  383. begin
  384. pthread_join(pthread_t(threadHandle), @LResultP);
  385. CWaitForThreadTerminate := dword(LResultP);
  386. end;
  387. function CThreadSetPriority (threadHandle : TThreadID; Prio: longint): boolean; {-15..+15, 0=normal}
  388. begin
  389. {$Warning ThreadSetPriority needs to be implemented}
  390. result:=false;
  391. end;
  392. function CThreadGetPriority (threadHandle : TThreadID): Integer;
  393. begin
  394. {$Warning ThreadGetPriority needs to be implemented}
  395. result:=0;
  396. end;
  397. function CGetCurrentThreadId : TThreadID;
  398. begin
  399. CGetCurrentThreadId := TThreadID (pthread_self());
  400. end;
  401. procedure CSetThreadDebugNameA(threadHandle: TThreadID; const ThreadName: AnsiString);
  402. {$if defined(Linux) or defined(Android)}
  403. var
  404. CuttedName: AnsiString;
  405. {$endif}
  406. begin
  407. {$if defined(Linux) or defined(Android)}
  408. if ThreadName = '' then
  409. Exit;
  410. {$ifdef dynpthreads}
  411. if Assigned(pthread_setname_np) then
  412. {$endif dynpthreads}
  413. begin
  414. // length restricted to 16 characters including terminating null byte
  415. CuttedName:=Copy(ThreadName, 1, 15);
  416. if threadHandle=TThreadID(-1) then
  417. begin
  418. pthread_setname_np(pthread_self(), @CuttedName[1]);
  419. end
  420. else
  421. begin
  422. pthread_setname_np(pthread_t(threadHandle), @CuttedName[1]);
  423. end;
  424. end;
  425. {$else}
  426. {$Warning SetThreadDebugName needs to be implemented}
  427. {$endif}
  428. end;
  429. procedure CSetThreadDebugNameU(threadHandle: TThreadID; const ThreadName: UnicodeString);
  430. begin
  431. {$if defined(Linux) or defined(Android)}
  432. {$ifdef dynpthreads}
  433. if Assigned(pthread_setname_np) then
  434. {$endif dynpthreads}
  435. begin
  436. CSetThreadDebugNameA(threadHandle, AnsiString(ThreadName));
  437. end;
  438. {$else}
  439. {$Warning SetThreadDebugName needs to be implemented}
  440. {$endif}
  441. end;
  442. {*****************************************************************************
  443. Delphi/Win32 compatibility
  444. *****************************************************************************}
  445. procedure CInitCriticalSection(var CS);
  446. var
  447. MAttr : pthread_mutexattr_t;
  448. res: longint;
  449. begin
  450. res:=pthread_mutexattr_init(@MAttr);
  451. if res=0 then
  452. begin
  453. res:=pthread_mutexattr_settype(@MAttr,longint(_PTHREAD_MUTEX_RECURSIVE));
  454. if res=0 then
  455. res := pthread_mutex_init(@CS,@MAttr)
  456. else
  457. { No recursive mutex support :/ }
  458. fpc_threaderror
  459. end
  460. else
  461. res:= pthread_mutex_init(@CS,NIL);
  462. pthread_mutexattr_destroy(@MAttr);
  463. if res <> 0 then
  464. fpc_threaderror;
  465. end;
  466. procedure CEnterCriticalSection(var CS);
  467. begin
  468. if pthread_mutex_lock(@CS) <> 0 then
  469. fpc_threaderror
  470. end;
  471. function CTryEnterCriticalSection(var CS):longint;
  472. begin
  473. if pthread_mutex_Trylock(@CS)=0 then
  474. result:=1 // succes
  475. else
  476. result:=0; // failure
  477. end;
  478. procedure CLeaveCriticalSection(var CS);
  479. begin
  480. if pthread_mutex_unlock(@CS) <> 0 then
  481. fpc_threaderror
  482. end;
  483. procedure CDoneCriticalSection(var CS);
  484. begin
  485. { unlock as long as unlocking works to unlock it if it is recursive
  486. some Delphi code might call this function with a locked mutex }
  487. while pthread_mutex_unlock(@CS)=0 do
  488. ;
  489. if pthread_mutex_destroy(@CS) <> 0 then
  490. fpc_threaderror;
  491. end;
  492. {*****************************************************************************
  493. Semaphore routines
  494. *****************************************************************************}
  495. type
  496. TPthreadCondition = pthread_cond_t;
  497. TPthreadMutex = pthread_mutex_t;
  498. Tbasiceventstate=record
  499. FCondVar: TPthreadCondition;
  500. {$if defined(Linux) and not defined(Android)}
  501. FAttr: pthread_condattr_t;
  502. FClockID: longint;
  503. {$ifend}
  504. FEventSection: TPthreadMutex;
  505. FWaiters: longint;
  506. FIsSet,
  507. FManualReset,
  508. FDestroying : Boolean;
  509. end;
  510. plocaleventstate = ^tbasiceventstate;
  511. // peventstate=pointer;
  512. Const
  513. wrSignaled = 0;
  514. wrTimeout = 1;
  515. wrAbandoned= 2;
  516. wrError = 3;
  517. function IntBasicEventCreate(EventAttributes : Pointer; AManualReset,InitialState : Boolean;const Name : ansistring):pEventState;
  518. var
  519. MAttr : pthread_mutexattr_t;
  520. res : cint;
  521. {$if defined(Linux) and not defined(Android)}
  522. timespec: ttimespec;
  523. {$ifend}
  524. begin
  525. new(plocaleventstate(result));
  526. plocaleventstate(result)^.FManualReset:=AManualReset;
  527. plocaleventstate(result)^.FWaiters:=0;
  528. plocaleventstate(result)^.FDestroying:=False;
  529. plocaleventstate(result)^.FIsSet:=InitialState;
  530. {$if defined(Linux) and not defined(Android)}
  531. res := pthread_condattr_init(@plocaleventstate(result)^.FAttr);
  532. if (res <> 0) then
  533. begin
  534. FreeMem(result);
  535. fpc_threaderror;
  536. end;
  537. if clock_gettime(CLOCK_MONOTONIC_RAW, @timespec) = 0 then
  538. begin
  539. res := pthread_condattr_setclock(@plocaleventstate(result)^.FAttr, CLOCK_MONOTONIC_RAW);
  540. end
  541. else
  542. begin
  543. res := -1; // No support for CLOCK_MONOTONIC_RAW
  544. end;
  545. if (res = 0) then
  546. begin
  547. plocaleventstate(result)^.FClockID := CLOCK_MONOTONIC_RAW;
  548. end
  549. else
  550. begin
  551. res := pthread_condattr_setclock(@plocaleventstate(result)^.FAttr, CLOCK_MONOTONIC);
  552. if (res = 0) then
  553. begin
  554. plocaleventstate(result)^.FClockID := CLOCK_MONOTONIC;
  555. end
  556. else
  557. begin
  558. pthread_condattr_destroy(@plocaleventstate(result)^.FAttr);
  559. FreeMem(result);
  560. fpc_threaderror;
  561. end;
  562. end;
  563. res := pthread_cond_init(@plocaleventstate(result)^.FCondVar, @plocaleventstate(result)^.FAttr);
  564. if (res <> 0) then
  565. begin
  566. pthread_condattr_destroy(@plocaleventstate(result)^.FAttr);
  567. FreeMem(result);
  568. fpc_threaderror;
  569. end;
  570. {$else}
  571. res := pthread_cond_init(@plocaleventstate(result)^.FCondVar, nil);
  572. if (res <> 0) then
  573. begin
  574. FreeMem(result);
  575. fpc_threaderror;
  576. end;
  577. {$ifend}
  578. res:=pthread_mutexattr_init(@MAttr);
  579. if res=0 then
  580. begin
  581. res:=pthread_mutexattr_settype(@MAttr,longint(_PTHREAD_MUTEX_RECURSIVE));
  582. if Res=0 then
  583. Res:=pthread_mutex_init(@plocaleventstate(result)^.feventsection,@MAttr)
  584. else
  585. res:=pthread_mutex_init(@plocaleventstate(result)^.feventsection,nil);
  586. end
  587. else
  588. res:=pthread_mutex_init(@plocaleventstate(result)^.feventsection,nil);
  589. pthread_mutexattr_destroy(@MAttr);
  590. if res <> 0 then
  591. begin
  592. pthread_cond_destroy(@plocaleventstate(result)^.FCondVar);
  593. {$if defined(Linux) and not defined(Android)}
  594. pthread_condattr_destroy(@plocaleventstate(result)^.FAttr);
  595. {$ifend}
  596. FreeMem(result);
  597. fpc_threaderror;
  598. end;
  599. end;
  600. procedure Intbasiceventdestroy(state:peventstate);
  601. begin
  602. { safely mark that we are destroying this event }
  603. pthread_mutex_lock(@plocaleventstate(state)^.feventsection);
  604. plocaleventstate(state)^.FDestroying:=true;
  605. { send a signal to all threads that are waiting }
  606. pthread_cond_broadcast(@plocaleventstate(state)^.FCondVar);
  607. pthread_mutex_unlock(@plocaleventstate(state)^.feventsection);
  608. { now wait until they've finished their business }
  609. while (plocaleventstate(state)^.FWaiters <> 0) do
  610. cThreadSwitch;
  611. { and clean up }
  612. pthread_cond_destroy(@plocaleventstate(state)^.Fcondvar);
  613. {$if defined(Linux) and not defined(Android)}
  614. pthread_condattr_destroy(@plocaleventstate(state)^.FAttr);
  615. {$ifend}
  616. pthread_mutex_destroy(@plocaleventstate(state)^.FEventSection);
  617. dispose(plocaleventstate(state));
  618. end;
  619. procedure IntbasiceventResetEvent(state:peventstate);
  620. begin
  621. pthread_mutex_lock(@plocaleventstate(state)^.feventsection);
  622. plocaleventstate(state)^.fisset:=false;
  623. pthread_mutex_unlock(@plocaleventstate(state)^.feventsection);
  624. end;
  625. procedure IntbasiceventSetEvent(state:peventstate);
  626. begin
  627. pthread_mutex_lock(@plocaleventstate(state)^.feventsection);
  628. plocaleventstate(state)^.Fisset:=true;
  629. if not(plocaleventstate(state)^.FManualReset) then
  630. pthread_cond_signal(@plocaleventstate(state)^.Fcondvar)
  631. else
  632. pthread_cond_broadcast(@plocaleventstate(state)^.Fcondvar);
  633. pthread_mutex_unlock(@plocaleventstate(state)^.feventsection);
  634. end;
  635. function IntbasiceventWaitFor(Timeout : Cardinal;state:peventstate) : longint;
  636. var
  637. timespec: ttimespec;
  638. errres: cint;
  639. isset: boolean;
  640. tnow : timeval;
  641. begin
  642. { safely check whether we are being destroyed, if so immediately return. }
  643. { otherwise (under the same mutex) increase the number of waiters }
  644. pthread_mutex_lock(@plocaleventstate(state)^.feventsection);
  645. if (plocaleventstate(state)^.FDestroying) then
  646. begin
  647. pthread_mutex_unlock(@plocaleventstate(state)^.feventsection);
  648. result := wrAbandoned;
  649. exit;
  650. end;
  651. { not a regular inc() because it may happen simulatneously with the }
  652. { interlockeddecrement() at the end }
  653. interlockedincrement(plocaleventstate(state)^.FWaiters);
  654. //Wait without timeout using pthread_cond_wait
  655. if Timeout = $FFFFFFFF then
  656. begin
  657. while (not plocaleventstate(state)^.FIsSet) and (not plocaleventstate(state)^.FDestroying) do
  658. pthread_cond_wait(@plocaleventstate(state)^.Fcondvar, @plocaleventstate(state)^.feventsection);
  659. end
  660. else
  661. begin
  662. //Wait with timeout using pthread_cond_timedwait
  663. {$if defined(Linux) and not defined(Android)}
  664. if clock_gettime(plocaleventstate(state)^.FClockID, @timespec) <> 0 then
  665. begin
  666. Result := Ord(wrError);
  667. Exit;
  668. end;
  669. timespec.tv_sec := timespec.tv_sec + (clong(timeout) div 1000);
  670. timespec.tv_nsec := ((clong(timeout) mod 1000) * 1000000) + (timespec.tv_nsec);
  671. {$else}
  672. // TODO: FIX-ME: Also use monotonic clock for other *nix targets
  673. fpgettimeofday(@tnow, nil);
  674. timespec.tv_sec := tnow.tv_sec + (clong(timeout) div 1000);
  675. timespec.tv_nsec := ((clong(timeout) mod 1000) * 1000000) + (tnow.tv_usec * 1000);
  676. {$ifend}
  677. if timespec.tv_nsec >= 1000000000 then
  678. begin
  679. inc(timespec.tv_sec);
  680. dec(timespec.tv_nsec, 1000000000);
  681. end;
  682. errres := 0;
  683. while (not plocaleventstate(state)^.FDestroying) and
  684. (not plocaleventstate(state)^.FIsSet) and
  685. (errres<>ESysETIMEDOUT) do
  686. errres := pthread_cond_timedwait(@plocaleventstate(state)^.Fcondvar,
  687. @plocaleventstate(state)^.feventsection,
  688. @timespec);
  689. end;
  690. isset := plocaleventstate(state)^.FIsSet;
  691. { if ManualReset=false, reset the event immediately. }
  692. if (plocaleventstate(state)^.FManualReset=false) then
  693. plocaleventstate(state)^.FIsSet := false;
  694. //check the results...
  695. if plocaleventstate(state)^.FDestroying then
  696. Result := wrAbandoned
  697. else
  698. if IsSet then
  699. Result := wrSignaled
  700. else
  701. begin
  702. if errres=ESysETIMEDOUT then
  703. Result := wrTimeout
  704. else
  705. Result := wrError;
  706. end;
  707. pthread_mutex_unlock(@plocaleventstate(state)^.feventsection);
  708. { don't put this above the previous pthread_mutex_unlock, because }
  709. { otherwise we can get errors in case an object is destroyed between }
  710. { end of the wait/sleep loop and the signalling above. }
  711. { The pthread_mutex_unlock above takes care of the memory barrier }
  712. interlockeddecrement(plocaleventstate(state)^.FWaiters);
  713. end;
  714. function intRTLEventCreate: PRTLEvent;
  715. var p:pintrtlevent;
  716. begin
  717. new(p);
  718. if not assigned(p) then
  719. fpc_threaderror;
  720. if pthread_cond_init(@p^.condvar, nil)<>0 then
  721. begin
  722. dispose(p);
  723. fpc_threaderror;
  724. end;
  725. if pthread_mutex_init(@p^.mutex, nil)<>0 then
  726. begin
  727. pthread_cond_destroy(@p^.condvar);
  728. dispose(p);
  729. fpc_threaderror;
  730. end;
  731. p^.isset:=false;
  732. result:=PRTLEVENT(p);
  733. end;
  734. procedure intRTLEventDestroy(AEvent: PRTLEvent);
  735. var p:pintrtlevent;
  736. begin
  737. p:=pintrtlevent(aevent);
  738. pthread_cond_destroy(@p^.condvar);
  739. pthread_mutex_destroy(@p^.mutex);
  740. dispose(p);
  741. end;
  742. procedure intRTLEventSetEvent(AEvent: PRTLEvent);
  743. var p:pintrtlevent;
  744. begin
  745. p:=pintrtlevent(aevent);
  746. pthread_mutex_lock(@p^.mutex);
  747. p^.isset:=true;
  748. pthread_cond_signal(@p^.condvar);
  749. pthread_mutex_unlock(@p^.mutex);
  750. end;
  751. procedure intRTLEventResetEvent(AEvent: PRTLEvent);
  752. var p:pintrtlevent;
  753. begin
  754. p:=pintrtlevent(aevent);
  755. pthread_mutex_lock(@p^.mutex);
  756. p^.isset:=false;
  757. pthread_mutex_unlock(@p^.mutex);
  758. end;
  759. procedure intRTLEventWaitFor(AEvent: PRTLEvent);
  760. var p:pintrtlevent;
  761. begin
  762. p:=pintrtlevent(aevent);
  763. pthread_mutex_lock(@p^.mutex);
  764. while not p^.isset do pthread_cond_wait(@p^.condvar, @p^.mutex);
  765. p^.isset:=false;
  766. pthread_mutex_unlock(@p^.mutex);
  767. end;
  768. procedure intRTLEventWaitForTimeout(AEvent: PRTLEvent;timeout : longint);
  769. var
  770. p : pintrtlevent;
  771. errres : cint;
  772. timespec : ttimespec;
  773. tnow : timeval;
  774. begin
  775. p:=pintrtlevent(aevent);
  776. fpgettimeofday(@tnow,nil);
  777. timespec.tv_sec:=tnow.tv_sec+(timeout div 1000);
  778. timespec.tv_nsec:=(timeout mod 1000)*1000000 + tnow.tv_usec*1000;
  779. if timespec.tv_nsec >= 1000000000 then
  780. begin
  781. inc(timespec.tv_sec);
  782. dec(timespec.tv_nsec, 1000000000);
  783. end;
  784. errres:=0;
  785. pthread_mutex_lock(@p^.mutex);
  786. while (not p^.isset) and
  787. (errres <> ESysETIMEDOUT) do
  788. begin
  789. errres:=pthread_cond_timedwait(@p^.condvar, @p^.mutex, @timespec);
  790. end;
  791. p^.isset:=false;
  792. pthread_mutex_unlock(@p^.mutex);
  793. end;
  794. type
  795. threadmethod = procedure of object;
  796. Function CInitThreads : Boolean;
  797. begin
  798. {$ifdef DEBUG_MT}
  799. Writeln('Entering InitThreads.');
  800. {$endif}
  801. {$ifndef dynpthreads}
  802. Result:=True;
  803. {$else}
  804. Result:=LoadPthreads;
  805. {$endif}
  806. ThreadID := TThreadID (pthread_self());
  807. {$ifdef DEBUG_MT}
  808. Writeln('InitThreads : ',Result);
  809. {$endif DEBUG_MT}
  810. // We assume that if you set the thread manager, the application is multithreading.
  811. InitCTLS;
  812. end;
  813. Function CDoneThreads : Boolean;
  814. begin
  815. {$ifndef dynpthreads}
  816. Result:=True;
  817. {$else}
  818. Result:=UnloadPthreads;
  819. {$endif}
  820. end;
  821. Var
  822. CThreadManager : TThreadManager;
  823. Procedure SetCThreadManager;
  824. begin
  825. With CThreadManager do begin
  826. InitManager :=@CInitThreads;
  827. DoneManager :=@CDoneThreads;
  828. BeginThread :=@CBeginThread;
  829. EndThread :=@CEndThread;
  830. SuspendThread :=@CSuspendThread;
  831. ResumeThread :=@CResumeThread;
  832. KillThread :=@CKillThread;
  833. ThreadSwitch :=@CThreadSwitch;
  834. CloseThread :=@CCloseThread;
  835. WaitForThreadTerminate :=@CWaitForThreadTerminate;
  836. ThreadSetPriority :=@CThreadSetPriority;
  837. ThreadGetPriority :=@CThreadGetPriority;
  838. GetCurrentThreadId :=@CGetCurrentThreadId;
  839. SetThreadDebugNameA :=@CSetThreadDebugNameA;
  840. SetThreadDebugNameU :=@CSetThreadDebugNameU;
  841. InitCriticalSection :=@CInitCriticalSection;
  842. DoneCriticalSection :=@CDoneCriticalSection;
  843. EnterCriticalSection :=@CEnterCriticalSection;
  844. TryEnterCriticalSection:=@CTryEnterCriticalSection;
  845. LeaveCriticalSection :=@CLeaveCriticalSection;
  846. InitThreadVar :=@CInitThreadVar;
  847. RelocateThreadVar :=@CRelocateThreadVar;
  848. AllocateThreadVars :=@CAllocateThreadVars;
  849. ReleaseThreadVars :=@CReleaseThreadVars;
  850. BasicEventCreate :=@intBasicEventCreate;
  851. BasicEventDestroy :=@intBasicEventDestroy;
  852. BasicEventResetEvent :=@intBasicEventResetEvent;
  853. BasicEventSetEvent :=@intBasicEventSetEvent;
  854. BasiceventWaitFor :=@intBasiceventWaitFor;
  855. rtlEventCreate :=@intrtlEventCreate;
  856. rtlEventDestroy :=@intrtlEventDestroy;
  857. rtlEventSetEvent :=@intrtlEventSetEvent;
  858. rtlEventResetEvent :=@intrtlEventResetEvent;
  859. rtleventWaitForTimeout :=@intrtleventWaitForTimeout;
  860. rtleventWaitFor :=@intrtleventWaitFor;
  861. end;
  862. SetThreadManager(CThreadManager);
  863. end;
  864. initialization
  865. if ThreadingAlreadyUsed then
  866. begin
  867. writeln('Threading has been used before cthreads was initialized.');
  868. writeln('Make cthreads one of the first units in your uses clause.');
  869. runerror(211);
  870. end;
  871. SetCThreadManager;
  872. finalization
  873. end.