cthreads.pp 32 KB

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