cthreads.pp 30 KB

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