cthreads.pp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  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. {*****************************************************************************
  402. Delphi/Win32 compatibility
  403. *****************************************************************************}
  404. procedure CInitCriticalSection(var CS);
  405. var
  406. MAttr : pthread_mutexattr_t;
  407. res: longint;
  408. begin
  409. res:=pthread_mutexattr_init(@MAttr);
  410. if res=0 then
  411. begin
  412. res:=pthread_mutexattr_settype(@MAttr,longint(_PTHREAD_MUTEX_RECURSIVE));
  413. if res=0 then
  414. res := pthread_mutex_init(@CS,@MAttr)
  415. else
  416. { No recursive mutex support :/ }
  417. fpc_threaderror
  418. end
  419. else
  420. res:= pthread_mutex_init(@CS,NIL);
  421. pthread_mutexattr_destroy(@MAttr);
  422. if res <> 0 then
  423. fpc_threaderror;
  424. end;
  425. procedure CEnterCriticalSection(var CS);
  426. begin
  427. if pthread_mutex_lock(@CS) <> 0 then
  428. fpc_threaderror
  429. end;
  430. function CTryEnterCriticalSection(var CS):longint;
  431. begin
  432. if pthread_mutex_Trylock(@CS)=0 then
  433. result:=1 // succes
  434. else
  435. result:=0; // failure
  436. end;
  437. procedure CLeaveCriticalSection(var CS);
  438. begin
  439. if pthread_mutex_unlock(@CS) <> 0 then
  440. fpc_threaderror
  441. end;
  442. procedure CDoneCriticalSection(var CS);
  443. begin
  444. { unlock as long as unlocking works to unlock it if it is recursive
  445. some Delphi code might call this function with a locked mutex }
  446. while pthread_mutex_unlock(@CS)=0 do
  447. ;
  448. if pthread_mutex_destroy(@CS) <> 0 then
  449. fpc_threaderror;
  450. end;
  451. {*****************************************************************************
  452. Semaphore routines
  453. *****************************************************************************}
  454. type
  455. TPthreadCondition = pthread_cond_t;
  456. TPthreadMutex = pthread_mutex_t;
  457. Tbasiceventstate=record
  458. FCondVar: TPthreadCondition;
  459. {$if defined(Linux) and not defined(Android)}
  460. FAttr: pthread_condattr_t;
  461. FClockID: longint;
  462. {$ifend}
  463. FEventSection: TPthreadMutex;
  464. FWaiters: longint;
  465. FIsSet,
  466. FManualReset,
  467. FDestroying : Boolean;
  468. end;
  469. plocaleventstate = ^tbasiceventstate;
  470. // peventstate=pointer;
  471. Const
  472. wrSignaled = 0;
  473. wrTimeout = 1;
  474. wrAbandoned= 2;
  475. wrError = 3;
  476. function IntBasicEventCreate(EventAttributes : Pointer; AManualReset,InitialState : Boolean;const Name : ansistring):pEventState;
  477. var
  478. MAttr : pthread_mutexattr_t;
  479. res : cint;
  480. {$if defined(Linux) and not defined(Android)}
  481. timespec: ttimespec;
  482. {$ifend}
  483. begin
  484. new(plocaleventstate(result));
  485. plocaleventstate(result)^.FManualReset:=AManualReset;
  486. plocaleventstate(result)^.FWaiters:=0;
  487. plocaleventstate(result)^.FDestroying:=False;
  488. plocaleventstate(result)^.FIsSet:=InitialState;
  489. {$if defined(Linux) and not defined(Android)}
  490. res := pthread_condattr_init(@plocaleventstate(result)^.FAttr);
  491. if (res <> 0) then
  492. begin
  493. FreeMem(result);
  494. fpc_threaderror;
  495. end;
  496. if clock_gettime(CLOCK_MONOTONIC_RAW, @timespec) = 0 then
  497. begin
  498. res := pthread_condattr_setclock(@plocaleventstate(result)^.FAttr, CLOCK_MONOTONIC_RAW);
  499. end
  500. else
  501. begin
  502. res := -1; // No support for CLOCK_MONOTONIC_RAW
  503. end;
  504. if (res = 0) then
  505. begin
  506. plocaleventstate(result)^.FClockID := CLOCK_MONOTONIC_RAW;
  507. end
  508. else
  509. begin
  510. res := pthread_condattr_setclock(@plocaleventstate(result)^.FAttr, CLOCK_MONOTONIC);
  511. if (res = 0) then
  512. begin
  513. plocaleventstate(result)^.FClockID := CLOCK_MONOTONIC;
  514. end
  515. else
  516. begin
  517. pthread_condattr_destroy(@plocaleventstate(result)^.FAttr);
  518. FreeMem(result);
  519. fpc_threaderror;
  520. end;
  521. end;
  522. res := pthread_cond_init(@plocaleventstate(result)^.FCondVar, @plocaleventstate(result)^.FAttr);
  523. if (res <> 0) then
  524. begin
  525. pthread_condattr_destroy(@plocaleventstate(result)^.FAttr);
  526. FreeMem(result);
  527. fpc_threaderror;
  528. end;
  529. {$else}
  530. res := pthread_cond_init(@plocaleventstate(result)^.FCondVar, nil);
  531. if (res <> 0) then
  532. begin
  533. FreeMem(result);
  534. fpc_threaderror;
  535. end;
  536. {$ifend}
  537. res:=pthread_mutexattr_init(@MAttr);
  538. if res=0 then
  539. begin
  540. res:=pthread_mutexattr_settype(@MAttr,longint(_PTHREAD_MUTEX_RECURSIVE));
  541. if Res=0 then
  542. Res:=pthread_mutex_init(@plocaleventstate(result)^.feventsection,@MAttr)
  543. else
  544. res:=pthread_mutex_init(@plocaleventstate(result)^.feventsection,nil);
  545. end
  546. else
  547. res:=pthread_mutex_init(@plocaleventstate(result)^.feventsection,nil);
  548. pthread_mutexattr_destroy(@MAttr);
  549. if res <> 0 then
  550. begin
  551. pthread_cond_destroy(@plocaleventstate(result)^.FCondVar);
  552. {$if defined(Linux) and not defined(Android)}
  553. pthread_condattr_destroy(@plocaleventstate(result)^.FAttr);
  554. {$ifend}
  555. FreeMem(result);
  556. fpc_threaderror;
  557. end;
  558. end;
  559. procedure Intbasiceventdestroy(state:peventstate);
  560. begin
  561. { safely mark that we are destroying this event }
  562. pthread_mutex_lock(@plocaleventstate(state)^.feventsection);
  563. plocaleventstate(state)^.FDestroying:=true;
  564. { send a signal to all threads that are waiting }
  565. pthread_cond_broadcast(@plocaleventstate(state)^.FCondVar);
  566. pthread_mutex_unlock(@plocaleventstate(state)^.feventsection);
  567. { now wait until they've finished their business }
  568. while (plocaleventstate(state)^.FWaiters <> 0) do
  569. cThreadSwitch;
  570. { and clean up }
  571. pthread_cond_destroy(@plocaleventstate(state)^.Fcondvar);
  572. {$if defined(Linux) and not defined(Android)}
  573. pthread_condattr_destroy(@plocaleventstate(state)^.FAttr);
  574. {$ifend}
  575. pthread_mutex_destroy(@plocaleventstate(state)^.FEventSection);
  576. dispose(plocaleventstate(state));
  577. end;
  578. procedure IntbasiceventResetEvent(state:peventstate);
  579. begin
  580. pthread_mutex_lock(@plocaleventstate(state)^.feventsection);
  581. plocaleventstate(state)^.fisset:=false;
  582. pthread_mutex_unlock(@plocaleventstate(state)^.feventsection);
  583. end;
  584. procedure IntbasiceventSetEvent(state:peventstate);
  585. begin
  586. pthread_mutex_lock(@plocaleventstate(state)^.feventsection);
  587. plocaleventstate(state)^.Fisset:=true;
  588. if not(plocaleventstate(state)^.FManualReset) then
  589. pthread_cond_signal(@plocaleventstate(state)^.Fcondvar)
  590. else
  591. pthread_cond_broadcast(@plocaleventstate(state)^.Fcondvar);
  592. pthread_mutex_unlock(@plocaleventstate(state)^.feventsection);
  593. end;
  594. function IntbasiceventWaitFor(Timeout : Cardinal;state:peventstate) : longint;
  595. var
  596. timespec: ttimespec;
  597. errres: cint;
  598. isset: boolean;
  599. tnow : timeval;
  600. begin
  601. { safely check whether we are being destroyed, if so immediately return. }
  602. { otherwise (under the same mutex) increase the number of waiters }
  603. pthread_mutex_lock(@plocaleventstate(state)^.feventsection);
  604. if (plocaleventstate(state)^.FDestroying) then
  605. begin
  606. pthread_mutex_unlock(@plocaleventstate(state)^.feventsection);
  607. result := wrAbandoned;
  608. exit;
  609. end;
  610. { not a regular inc() because it may happen simulatneously with the }
  611. { interlockeddecrement() at the end }
  612. interlockedincrement(plocaleventstate(state)^.FWaiters);
  613. //Wait without timeout using pthread_cond_wait
  614. if Timeout = $FFFFFFFF then
  615. begin
  616. while (not plocaleventstate(state)^.FIsSet) and (not plocaleventstate(state)^.FDestroying) do
  617. pthread_cond_wait(@plocaleventstate(state)^.Fcondvar, @plocaleventstate(state)^.feventsection);
  618. end
  619. else
  620. begin
  621. //Wait with timeout using pthread_cond_timedwait
  622. {$if defined(Linux) and not defined(Android)}
  623. if clock_gettime(plocaleventstate(state)^.FClockID, @timespec) <> 0 then
  624. begin
  625. Result := Ord(wrError);
  626. Exit;
  627. end;
  628. timespec.tv_sec := timespec.tv_sec + (clong(timeout) div 1000);
  629. timespec.tv_nsec := ((clong(timeout) mod 1000) * 1000000) + (timespec.tv_nsec);
  630. {$else}
  631. // TODO: FIX-ME: Also use monotonic clock for other *nix targets
  632. fpgettimeofday(@tnow, nil);
  633. timespec.tv_sec := tnow.tv_sec + (clong(timeout) div 1000);
  634. timespec.tv_nsec := ((clong(timeout) mod 1000) * 1000000) + (tnow.tv_usec * 1000);
  635. {$ifend}
  636. if timespec.tv_nsec >= 1000000000 then
  637. begin
  638. inc(timespec.tv_sec);
  639. dec(timespec.tv_nsec, 1000000000);
  640. end;
  641. errres := 0;
  642. while (not plocaleventstate(state)^.FDestroying) and
  643. (not plocaleventstate(state)^.FIsSet) and
  644. (errres<>ESysETIMEDOUT) do
  645. errres := pthread_cond_timedwait(@plocaleventstate(state)^.Fcondvar,
  646. @plocaleventstate(state)^.feventsection,
  647. @timespec);
  648. end;
  649. isset := plocaleventstate(state)^.FIsSet;
  650. { if ManualReset=false, reset the event immediately. }
  651. if (plocaleventstate(state)^.FManualReset=false) then
  652. plocaleventstate(state)^.FIsSet := false;
  653. //check the results...
  654. if plocaleventstate(state)^.FDestroying then
  655. Result := wrAbandoned
  656. else
  657. if IsSet then
  658. Result := wrSignaled
  659. else
  660. begin
  661. if errres=ESysETIMEDOUT then
  662. Result := wrTimeout
  663. else
  664. Result := wrError;
  665. end;
  666. pthread_mutex_unlock(@plocaleventstate(state)^.feventsection);
  667. { don't put this above the previous pthread_mutex_unlock, because }
  668. { otherwise we can get errors in case an object is destroyed between }
  669. { end of the wait/sleep loop and the signalling above. }
  670. { The pthread_mutex_unlock above takes care of the memory barrier }
  671. interlockeddecrement(plocaleventstate(state)^.FWaiters);
  672. end;
  673. function intRTLEventCreate: PRTLEvent;
  674. var p:pintrtlevent;
  675. begin
  676. new(p);
  677. if not assigned(p) then
  678. fpc_threaderror;
  679. if pthread_cond_init(@p^.condvar, nil)<>0 then
  680. begin
  681. dispose(p);
  682. fpc_threaderror;
  683. end;
  684. if pthread_mutex_init(@p^.mutex, nil)<>0 then
  685. begin
  686. pthread_cond_destroy(@p^.condvar);
  687. dispose(p);
  688. fpc_threaderror;
  689. end;
  690. p^.isset:=false;
  691. result:=PRTLEVENT(p);
  692. end;
  693. procedure intRTLEventDestroy(AEvent: PRTLEvent);
  694. var p:pintrtlevent;
  695. begin
  696. p:=pintrtlevent(aevent);
  697. pthread_cond_destroy(@p^.condvar);
  698. pthread_mutex_destroy(@p^.mutex);
  699. dispose(p);
  700. end;
  701. procedure intRTLEventSetEvent(AEvent: PRTLEvent);
  702. var p:pintrtlevent;
  703. begin
  704. p:=pintrtlevent(aevent);
  705. pthread_mutex_lock(@p^.mutex);
  706. p^.isset:=true;
  707. pthread_cond_signal(@p^.condvar);
  708. pthread_mutex_unlock(@p^.mutex);
  709. end;
  710. procedure intRTLEventResetEvent(AEvent: PRTLEvent);
  711. var p:pintrtlevent;
  712. begin
  713. p:=pintrtlevent(aevent);
  714. pthread_mutex_lock(@p^.mutex);
  715. p^.isset:=false;
  716. pthread_mutex_unlock(@p^.mutex);
  717. end;
  718. procedure intRTLEventWaitFor(AEvent: PRTLEvent);
  719. var p:pintrtlevent;
  720. begin
  721. p:=pintrtlevent(aevent);
  722. pthread_mutex_lock(@p^.mutex);
  723. while not p^.isset do pthread_cond_wait(@p^.condvar, @p^.mutex);
  724. p^.isset:=false;
  725. pthread_mutex_unlock(@p^.mutex);
  726. end;
  727. procedure intRTLEventWaitForTimeout(AEvent: PRTLEvent;timeout : longint);
  728. var
  729. p : pintrtlevent;
  730. errres : cint;
  731. timespec : ttimespec;
  732. tnow : timeval;
  733. begin
  734. p:=pintrtlevent(aevent);
  735. fpgettimeofday(@tnow,nil);
  736. timespec.tv_sec:=tnow.tv_sec+(timeout div 1000);
  737. timespec.tv_nsec:=(timeout mod 1000)*1000000 + tnow.tv_usec*1000;
  738. if timespec.tv_nsec >= 1000000000 then
  739. begin
  740. inc(timespec.tv_sec);
  741. dec(timespec.tv_nsec, 1000000000);
  742. end;
  743. errres:=0;
  744. pthread_mutex_lock(@p^.mutex);
  745. while (not p^.isset) and
  746. (errres <> ESysETIMEDOUT) do
  747. begin
  748. errres:=pthread_cond_timedwait(@p^.condvar, @p^.mutex, @timespec);
  749. end;
  750. p^.isset:=false;
  751. pthread_mutex_unlock(@p^.mutex);
  752. end;
  753. type
  754. threadmethod = procedure of object;
  755. Function CInitThreads : Boolean;
  756. begin
  757. {$ifdef DEBUG_MT}
  758. Writeln('Entering InitThreads.');
  759. {$endif}
  760. {$ifndef dynpthreads}
  761. Result:=True;
  762. {$else}
  763. Result:=LoadPthreads;
  764. {$endif}
  765. ThreadID := TThreadID (pthread_self());
  766. {$ifdef DEBUG_MT}
  767. Writeln('InitThreads : ',Result);
  768. {$endif DEBUG_MT}
  769. // We assume that if you set the thread manager, the application is multithreading.
  770. InitCTLS;
  771. end;
  772. Function CDoneThreads : Boolean;
  773. begin
  774. {$ifndef dynpthreads}
  775. Result:=True;
  776. {$else}
  777. Result:=UnloadPthreads;
  778. {$endif}
  779. end;
  780. Var
  781. CThreadManager : TThreadManager;
  782. Procedure SetCThreadManager;
  783. begin
  784. With CThreadManager do begin
  785. InitManager :=@CInitThreads;
  786. DoneManager :=@CDoneThreads;
  787. BeginThread :=@CBeginThread;
  788. EndThread :=@CEndThread;
  789. SuspendThread :=@CSuspendThread;
  790. ResumeThread :=@CResumeThread;
  791. KillThread :=@CKillThread;
  792. ThreadSwitch :=@CThreadSwitch;
  793. CloseThread :=@CCloseThread;
  794. WaitForThreadTerminate :=@CWaitForThreadTerminate;
  795. ThreadSetPriority :=@CThreadSetPriority;
  796. ThreadGetPriority :=@CThreadGetPriority;
  797. GetCurrentThreadId :=@CGetCurrentThreadId;
  798. InitCriticalSection :=@CInitCriticalSection;
  799. DoneCriticalSection :=@CDoneCriticalSection;
  800. EnterCriticalSection :=@CEnterCriticalSection;
  801. TryEnterCriticalSection:=@CTryEnterCriticalSection;
  802. LeaveCriticalSection :=@CLeaveCriticalSection;
  803. InitThreadVar :=@CInitThreadVar;
  804. RelocateThreadVar :=@CRelocateThreadVar;
  805. AllocateThreadVars :=@CAllocateThreadVars;
  806. ReleaseThreadVars :=@CReleaseThreadVars;
  807. BasicEventCreate :=@intBasicEventCreate;
  808. BasicEventDestroy :=@intBasicEventDestroy;
  809. BasicEventResetEvent :=@intBasicEventResetEvent;
  810. BasicEventSetEvent :=@intBasicEventSetEvent;
  811. BasiceventWaitFor :=@intBasiceventWaitFor;
  812. rtlEventCreate :=@intrtlEventCreate;
  813. rtlEventDestroy :=@intrtlEventDestroy;
  814. rtlEventSetEvent :=@intrtlEventSetEvent;
  815. rtlEventResetEvent :=@intrtlEventResetEvent;
  816. rtleventWaitForTimeout :=@intrtleventWaitForTimeout;
  817. rtleventWaitFor :=@intrtleventWaitFor;
  818. end;
  819. SetThreadManager(CThreadManager);
  820. end;
  821. initialization
  822. if ThreadingAlreadyUsed then
  823. begin
  824. writeln('Threading has been used before cthreads was initialized.');
  825. writeln('Make cthreads one of the first units in your uses clause.');
  826. runerror(211);
  827. end;
  828. SetCThreadManager;
  829. finalization
  830. end.