cthreads.pp 30 KB

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