cthreads.pp 27 KB

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