cthreads.pp 31 KB

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