cthreads.pp 27 KB

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