cthreads.pp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044
  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. {$ifdef DEBUG_MT}
  305. writeln('BeginThread returning ',ptrint(CBeginThread));
  306. {$endif DEBUG_MT}
  307. end;
  308. procedure CEndThread(ExitCode : DWord);
  309. begin
  310. DoneThread;
  311. pthread_detach(pthread_t(pthread_self()));
  312. pthread_exit(pointer(ptrint(ExitCode)));
  313. end;
  314. function CSuspendThread (threadHandle : TThreadID) : dword;
  315. begin
  316. { pthread_kill(SIGSTOP) cannot be used, because posix-compliant
  317. implementations then freeze the entire process instead of only
  318. the target thread. Suspending a particular thread is not
  319. supported by posix nor by most *nix implementations, presumably
  320. because of concerns mentioned in E.4 at
  321. http://pauillac.inria.fr/~xleroy/linuxthreads/faq.html#E and in
  322. http://java.sun.com/j2se/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html
  323. }
  324. // result := pthread_kill(threadHandle,SIGSTOP);
  325. result:=dword(-1);
  326. end;
  327. function CResumeThread (threadHandle : TThreadID) : dword;
  328. begin
  329. result:=dword(-1);
  330. end;
  331. procedure sched_yield; cdecl; external 'c' name 'sched_yield';
  332. procedure CThreadSwitch; {give time to other threads}
  333. begin
  334. { At least on Mac OS X, the pthread_yield_np calls through to this. }
  335. { Further, sched_yield is in POSIX and supported on FreeBSD 4+, }
  336. { Linux, Mac OS X and Solaris, while the thread-specific yield }
  337. { routines are called differently everywhere and non-standard. }
  338. sched_yield;
  339. end;
  340. function CKillThread (threadHandle : TThreadID) : dword;
  341. begin
  342. pthread_detach(pthread_t(threadHandle));
  343. {$ifndef android}
  344. CKillThread := pthread_cancel(pthread_t(threadHandle));
  345. {$else}
  346. CKillThread := dword(-1);
  347. {$endif}
  348. end;
  349. function CCloseThread (threadHandle : TThreadID) : dword;
  350. begin
  351. result:=0;
  352. end;
  353. function CWaitForThreadTerminate (threadHandle : TThreadID; TimeoutMs : longint) : dword; {0=no timeout}
  354. var
  355. LResultP: Pointer;
  356. begin
  357. pthread_join(pthread_t(threadHandle), @LResultP);
  358. CWaitForThreadTerminate := dword(LResultP);
  359. end;
  360. function CThreadSetPriority (threadHandle : TThreadID; Prio: longint): boolean; {-15..+15, 0=normal}
  361. begin
  362. {$Warning ThreadSetPriority needs to be implemented}
  363. result:=false;
  364. end;
  365. function CThreadGetPriority (threadHandle : TThreadID): Integer;
  366. begin
  367. {$Warning ThreadGetPriority needs to be implemented}
  368. result:=0;
  369. end;
  370. function CGetCurrentThreadId : TThreadID;
  371. begin
  372. CGetCurrentThreadId := TThreadID (pthread_self());
  373. end;
  374. {*****************************************************************************
  375. Delphi/Win32 compatibility
  376. *****************************************************************************}
  377. procedure CInitCriticalSection(var CS);
  378. var
  379. MAttr : pthread_mutexattr_t;
  380. res: longint;
  381. begin
  382. res:=pthread_mutexattr_init(@MAttr);
  383. if res=0 then
  384. begin
  385. res:=pthread_mutexattr_settype(@MAttr,longint(_PTHREAD_MUTEX_RECURSIVE));
  386. if res=0 then
  387. res := pthread_mutex_init(@CS,@MAttr)
  388. else
  389. { No recursive mutex support :/ }
  390. fpc_threaderror
  391. end
  392. else
  393. res:= pthread_mutex_init(@CS,NIL);
  394. pthread_mutexattr_destroy(@MAttr);
  395. if res <> 0 then
  396. fpc_threaderror;
  397. end;
  398. procedure CEnterCriticalSection(var CS);
  399. begin
  400. if pthread_mutex_lock(@CS) <> 0 then
  401. fpc_threaderror
  402. end;
  403. function CTryEnterCriticalSection(var CS):longint;
  404. begin
  405. if pthread_mutex_Trylock(@CS)=0 then
  406. result:=1 // succes
  407. else
  408. result:=0; // failure
  409. end;
  410. procedure CLeaveCriticalSection(var CS);
  411. begin
  412. if pthread_mutex_unlock(@CS) <> 0 then
  413. fpc_threaderror
  414. end;
  415. procedure CDoneCriticalSection(var CS);
  416. begin
  417. { unlock as long as unlocking works to unlock it if it is recursive
  418. some Delphi code might call this function with a locked mutex }
  419. while pthread_mutex_unlock(@CS)=0 do
  420. ;
  421. if pthread_mutex_destroy(@CS) <> 0 then
  422. fpc_threaderror;
  423. end;
  424. {*****************************************************************************
  425. Semaphore routines
  426. *****************************************************************************}
  427. procedure cSemaphoreWait(const FSem: Pointer);
  428. var
  429. res: cint;
  430. err: cint;
  431. {$if not defined(has_sem_init) and not defined(has_sem_open)}
  432. b: byte;
  433. {$endif}
  434. begin
  435. {$if defined(has_sem_init) or defined(has_sem_open)}
  436. repeat
  437. res:=sem_wait(PSemaphore(FSem));
  438. err:=fpgetCerrno;
  439. until (res<>-1) or (err<>ESysEINTR);
  440. {$else}
  441. repeat
  442. res:=fpread(PFilDes(FSem)^[0], b, 1);
  443. err:=fpgeterrno;
  444. until (res<>-1) or ((err<>ESysEINTR) and (err<>ESysEAgain));
  445. {$endif}
  446. end;
  447. {$if defined(has_sem_timedwait)}
  448. function cSemaphoreTimedWait(const FSem: Pointer; const Timeout: ttimespec): cint;
  449. var
  450. res: cint;
  451. err: cint;
  452. begin
  453. repeat
  454. res:=sem_timedwait(PSemaphore(FSem), @Timeout);
  455. if res=0 then exit(0);
  456. err:=fpgetCerrno;
  457. until err<>ESysEINTR;
  458. result:=err;
  459. end;
  460. {$endif}
  461. procedure cSemaphorePost(const FSem: Pointer);
  462. {$if defined(has_sem_init) or defined(has_sem_open)}
  463. begin
  464. sem_post(PSemaphore(FSem));
  465. end;
  466. {$else}
  467. var
  468. writeres: cint;
  469. err: cint;
  470. b : byte;
  471. begin
  472. b:=0;
  473. repeat
  474. writeres:=fpwrite(PFilDes(FSem)^[1], b, 1);
  475. err:=fpgeterrno;
  476. until (writeres<>-1) or ((err<>ESysEINTR) and (err<>ESysEAgain));
  477. end;
  478. {$endif}
  479. function cSemaphoreTryWait(const FSem: pointer): TTryWaitResult;
  480. var
  481. res: cint;
  482. err: cint;
  483. {$if defined(has_sem_init) or defined(has_sem_open)}
  484. begin
  485. repeat
  486. res:=sem_trywait(FSem);
  487. err:=fpgetCerrno;
  488. until (res<>-1) or (err<>ESysEINTR);
  489. if (res=0) then
  490. result:=tw_semwasunlocked
  491. else if (err=ESysEAgain) then
  492. result:=tw_semwaslocked
  493. else
  494. result:=tw_error;
  495. {$else has_sem_init or has_sem_open}
  496. var
  497. fds: TFDSet;
  498. tv : timeval;
  499. begin
  500. tv.tv_sec:=0;
  501. tv.tv_usec:=0;
  502. fpFD_ZERO(fds);
  503. fpFD_SET(PFilDes(FSem)^[0],fds);
  504. repeat
  505. res:=fpselect(PFilDes(FSem)^[0]+1,@fds,nil,nil,@tv);
  506. err:=fpgeterrno;
  507. until (res>=0) or ((res=-1) and (err<>ESysEIntr));
  508. if (res>0) then
  509. begin
  510. cSemaphoreWait(FSem);
  511. result:=tw_semwasunlocked
  512. end
  513. else if (res=0) then
  514. result:=tw_semwaslocked
  515. else
  516. result:=tw_error;
  517. {$endif has_sem_init or has_sem_open}
  518. end;
  519. {$if defined(has_sem_open) and not defined(has_sem_init)}
  520. function cIntSemaphoreOpen(const name: pchar; initvalue: boolean): Pointer;
  521. var
  522. err: cint;
  523. begin
  524. repeat
  525. cIntSemaphoreOpen := sem_open(name,O_CREAT,0,ord(initvalue));
  526. err:=fpgetCerrno;
  527. until (ptrint(cIntSemaphoreOpen) <> SEM_FAILED) or (err <> ESysEINTR);
  528. if (ptrint(cIntSemaphoreOpen) <> SEM_FAILED) then
  529. { immediately unlink so the semaphore will be destroyed when the }
  530. { the process exits }
  531. sem_unlink(name)
  532. else
  533. { 0 is a valid for sem_open on some platforms; pointer(-1) shouldn't
  534. be valid anywhere, even for sem_init }
  535. cIntSemaphoreOpen:=pointer(-1);
  536. end;
  537. {$endif}
  538. function cIntSemaphoreInit(initvalue: boolean): Pointer;
  539. {$if defined(has_sem_open) and not defined(has_sem_init)}
  540. var
  541. tid: string[31];
  542. semname: string[63];
  543. {$endif}
  544. begin
  545. {$ifdef has_sem_init}
  546. cIntSemaphoreInit := GetMem(SizeOf(TSemaphore));
  547. if sem_init(PSemaphore(cIntSemaphoreInit), 0, ord(initvalue)) <> 0 then
  548. begin
  549. FreeMem(cIntSemaphoreInit);
  550. { 0 is a valid for sem_open on some platforms; pointer(-1) shouldn't
  551. be valid anywhere, even for sem_init }
  552. cIntSemaphoreInit:=pointer(-1);
  553. end;
  554. {$else}
  555. {$ifdef has_sem_open}
  556. { avoid a potential temporary nameclash with another process/thread }
  557. str(fpGetPid,semname);
  558. str(ptruint(pthread_self()),tid);
  559. semname:='/FPC'+semname+'T'+tid+#0;
  560. cIntSemaphoreInit:=cIntSemaphoreOpen(@semname[1],initvalue);
  561. {$else}
  562. cIntSemaphoreInit := GetMem(SizeOf(TFilDes));
  563. if (fppipe(PFilDes(cIntSemaphoreInit)^) <> 0) then
  564. begin
  565. FreeMem(cIntSemaphoreInit);
  566. { 0 is a valid for sem_open on some platforms; pointer(-1) shouldn't
  567. be valid anywhere, even for sem_init }
  568. cIntSemaphoreInit:=pointer(-1);
  569. end
  570. else if initvalue then
  571. cSemaphorePost(cIntSemaphoreInit);
  572. {$endif}
  573. {$endif}
  574. end;
  575. function cSemaphoreInit: Pointer;
  576. begin
  577. cSemaphoreInit:=cIntSemaphoreInit(false);
  578. end;
  579. procedure cSemaphoreDestroy(const FSem: Pointer);
  580. begin
  581. {$ifdef has_sem_init}
  582. sem_destroy(PSemaphore(FSem));
  583. FreeMem(FSem);
  584. {$else}
  585. {$ifdef has_sem_open}
  586. sem_close(PSemaphore(FSem));
  587. {$else has_sem_init}
  588. fpclose(PFilDes(FSem)^[0]);
  589. fpclose(PFilDes(FSem)^[1]);
  590. FreeMem(FSem);
  591. {$endif}
  592. {$endif}
  593. end;
  594. type
  595. TPthreadCondition = pthread_cond_t;
  596. TPthreadMutex = pthread_mutex_t;
  597. Tbasiceventstate=record
  598. FCondVar: TPthreadCondition;
  599. FEventSection: TPthreadMutex;
  600. FWaiters: longint;
  601. FIsSet,
  602. FManualReset,
  603. FDestroying : Boolean;
  604. end;
  605. plocaleventstate = ^tbasiceventstate;
  606. // peventstate=pointer;
  607. Const
  608. wrSignaled = 0;
  609. wrTimeout = 1;
  610. wrAbandoned= 2;
  611. wrError = 3;
  612. function IntBasicEventCreate(EventAttributes : Pointer; AManualReset,InitialState : Boolean;const Name : ansistring):pEventState;
  613. var
  614. MAttr : pthread_mutexattr_t;
  615. res : cint;
  616. begin
  617. new(plocaleventstate(result));
  618. plocaleventstate(result)^.FManualReset:=AManualReset;
  619. plocaleventstate(result)^.FWaiters:=0;
  620. plocaleventstate(result)^.FDestroying:=False;
  621. plocaleventstate(result)^.FIsSet:=InitialState;
  622. res := pthread_cond_init(@plocaleventstate(result)^.FCondVar, nil);
  623. if (res <> 0) then
  624. begin
  625. FreeMem(result);
  626. fpc_threaderror;
  627. end;
  628. res:=pthread_mutexattr_init(@MAttr);
  629. if res=0 then
  630. begin
  631. res:=pthread_mutexattr_settype(@MAttr,longint(_PTHREAD_MUTEX_RECURSIVE));
  632. if Res=0 then
  633. Res:=pthread_mutex_init(@plocaleventstate(result)^.feventsection,@MAttr)
  634. else
  635. res:=pthread_mutex_init(@plocaleventstate(result)^.feventsection,nil);
  636. end
  637. else
  638. res:=pthread_mutex_init(@plocaleventstate(result)^.feventsection,nil);
  639. pthread_mutexattr_destroy(@MAttr);
  640. if res <> 0 then
  641. begin
  642. pthread_cond_destroy(@plocaleventstate(result)^.FCondVar);
  643. FreeMem(result);
  644. fpc_threaderror;
  645. end;
  646. end;
  647. procedure Intbasiceventdestroy(state:peventstate);
  648. begin
  649. { safely mark that we are destroying this event }
  650. pthread_mutex_lock(@plocaleventstate(state)^.feventsection);
  651. plocaleventstate(state)^.FDestroying:=true;
  652. { send a signal to all threads that are waiting }
  653. pthread_cond_broadcast(@plocaleventstate(state)^.FCondVar);
  654. pthread_mutex_unlock(@plocaleventstate(state)^.feventsection);
  655. { now wait until they've finished their business }
  656. while (plocaleventstate(state)^.FWaiters <> 0) do
  657. cThreadSwitch;
  658. { and clean up }
  659. pthread_cond_destroy(@plocaleventstate(state)^.Fcondvar);
  660. pthread_mutex_destroy(@plocaleventstate(state)^.FEventSection);
  661. dispose(plocaleventstate(state));
  662. end;
  663. procedure IntbasiceventResetEvent(state:peventstate);
  664. begin
  665. pthread_mutex_lock(@plocaleventstate(state)^.feventsection);
  666. plocaleventstate(state)^.fisset:=false;
  667. pthread_mutex_unlock(@plocaleventstate(state)^.feventsection);
  668. end;
  669. procedure IntbasiceventSetEvent(state:peventstate);
  670. begin
  671. pthread_mutex_lock(@plocaleventstate(state)^.feventsection);
  672. plocaleventstate(state)^.Fisset:=true;
  673. if not(plocaleventstate(state)^.FManualReset) then
  674. pthread_cond_signal(@plocaleventstate(state)^.Fcondvar)
  675. else
  676. pthread_cond_broadcast(@plocaleventstate(state)^.Fcondvar);
  677. pthread_mutex_unlock(@plocaleventstate(state)^.feventsection);
  678. end;
  679. function IntbasiceventWaitFor(Timeout : Cardinal;state:peventstate) : longint;
  680. var
  681. timespec: ttimespec;
  682. errres: cint;
  683. isset: boolean;
  684. tnow : timeval;
  685. begin
  686. { safely check whether we are being destroyed, if so immediately return. }
  687. { otherwise (under the same mutex) increase the number of waiters }
  688. pthread_mutex_lock(@plocaleventstate(state)^.feventsection);
  689. if (plocaleventstate(state)^.FDestroying) then
  690. begin
  691. pthread_mutex_unlock(@plocaleventstate(state)^.feventsection);
  692. result := wrAbandoned;
  693. exit;
  694. end;
  695. { not a regular inc() because it may happen simulatneously with the }
  696. { interlockeddecrement() at the end }
  697. interlockedincrement(plocaleventstate(state)^.FWaiters);
  698. //Wait without timeout using pthread_cond_wait
  699. if Timeout = $FFFFFFFF then
  700. begin
  701. while (not plocaleventstate(state)^.FIsSet) and (not plocaleventstate(state)^.FDestroying) do
  702. pthread_cond_wait(@plocaleventstate(state)^.Fcondvar, @plocaleventstate(state)^.feventsection);
  703. end
  704. else
  705. begin
  706. //Wait with timeout using pthread_cont_timedwait
  707. fpgettimeofday(@tnow,nil);
  708. timespec.tv_sec := tnow.tv_sec + (clong(timeout) div 1000);
  709. timespec.tv_nsec := (clong(timeout) mod 1000)*1000000 + tnow.tv_usec*1000;
  710. if timespec.tv_nsec >= 1000000000 then
  711. begin
  712. inc(timespec.tv_sec);
  713. dec(timespec.tv_nsec, 1000000000);
  714. end;
  715. errres:=0;
  716. while (not plocaleventstate(state)^.FDestroying) and (not plocaleventstate(state)^.FIsSet) and (errres<>ESysETIMEDOUT) do
  717. errres:=pthread_cond_timedwait(@plocaleventstate(state)^.Fcondvar, @plocaleventstate(state)^.feventsection, @timespec);
  718. end;
  719. isset := plocaleventstate(state)^.FIsSet;
  720. { if ManualReset=false, reset the event immediately. }
  721. if (plocaleventstate(state)^.FManualReset=false) then
  722. plocaleventstate(state)^.FIsSet := false;
  723. //check the results...
  724. if plocaleventstate(state)^.FDestroying then
  725. Result := wrAbandoned
  726. else
  727. if IsSet then
  728. Result := wrSignaled
  729. else
  730. begin
  731. if errres=ESysETIMEDOUT then
  732. Result := wrTimeout
  733. else
  734. Result := wrError;
  735. end;
  736. pthread_mutex_unlock(@plocaleventstate(state)^.feventsection);
  737. { don't put this above the previous pthread_mutex_unlock, because }
  738. { otherwise we can get errors in case an object is destroyed between }
  739. { end of the wait/sleep loop and the signalling above. }
  740. { The pthread_mutex_unlock above takes care of the memory barrier }
  741. interlockeddecrement(plocaleventstate(state)^.FWaiters);
  742. end;
  743. function intRTLEventCreate: PRTLEvent;
  744. var p:pintrtlevent;
  745. begin
  746. new(p);
  747. pthread_cond_init(@p^.condvar, nil);
  748. pthread_mutex_init(@p^.mutex, nil);
  749. p^.isset:=false;
  750. result:=PRTLEVENT(p);
  751. end;
  752. procedure intRTLEventDestroy(AEvent: PRTLEvent);
  753. var p:pintrtlevent;
  754. begin
  755. p:=pintrtlevent(aevent);
  756. pthread_cond_destroy(@p^.condvar);
  757. pthread_mutex_destroy(@p^.mutex);
  758. dispose(p);
  759. end;
  760. procedure intRTLEventSetEvent(AEvent: PRTLEvent);
  761. var p:pintrtlevent;
  762. begin
  763. p:=pintrtlevent(aevent);
  764. pthread_mutex_lock(@p^.mutex);
  765. p^.isset:=true;
  766. pthread_cond_signal(@p^.condvar);
  767. pthread_mutex_unlock(@p^.mutex);
  768. end;
  769. procedure intRTLEventResetEvent(AEvent: PRTLEvent);
  770. var p:pintrtlevent;
  771. begin
  772. p:=pintrtlevent(aevent);
  773. pthread_mutex_lock(@p^.mutex);
  774. p^.isset:=false;
  775. pthread_mutex_unlock(@p^.mutex);
  776. end;
  777. procedure intRTLEventWaitFor(AEvent: PRTLEvent);
  778. var p:pintrtlevent;
  779. begin
  780. p:=pintrtlevent(aevent);
  781. pthread_mutex_lock(@p^.mutex);
  782. while not p^.isset do pthread_cond_wait(@p^.condvar, @p^.mutex);
  783. p^.isset:=false;
  784. pthread_mutex_unlock(@p^.mutex);
  785. end;
  786. procedure intRTLEventWaitForTimeout(AEvent: PRTLEvent;timeout : longint);
  787. var
  788. p : pintrtlevent;
  789. errres : cint;
  790. timespec : ttimespec;
  791. tnow : timeval;
  792. begin
  793. p:=pintrtlevent(aevent);
  794. fpgettimeofday(@tnow,nil);
  795. timespec.tv_sec:=tnow.tv_sec+(timeout div 1000);
  796. timespec.tv_nsec:=(timeout mod 1000)*1000000 + tnow.tv_usec*1000;
  797. if timespec.tv_nsec >= 1000000000 then
  798. begin
  799. inc(timespec.tv_sec);
  800. dec(timespec.tv_nsec, 1000000000);
  801. end;
  802. errres:=0;
  803. pthread_mutex_lock(@p^.mutex);
  804. while (not p^.isset) and
  805. (errres <> ESysETIMEDOUT) do
  806. begin
  807. errres:=pthread_cond_timedwait(@p^.condvar, @p^.mutex, @timespec);
  808. end;
  809. p^.isset:=false;
  810. pthread_mutex_unlock(@p^.mutex);
  811. end;
  812. type
  813. threadmethod = procedure of object;
  814. Function CInitThreads : Boolean;
  815. begin
  816. {$ifdef DEBUG_MT}
  817. Writeln('Entering InitThreads.');
  818. {$endif}
  819. {$ifndef dynpthreads}
  820. Result:=True;
  821. {$else}
  822. Result:=LoadPthreads;
  823. {$endif}
  824. ThreadID := TThreadID (pthread_self());
  825. {$ifdef DEBUG_MT}
  826. Writeln('InitThreads : ',Result);
  827. {$endif DEBUG_MT}
  828. end;
  829. Function CDoneThreads : Boolean;
  830. begin
  831. {$ifndef dynpthreads}
  832. Result:=True;
  833. {$else}
  834. Result:=UnloadPthreads;
  835. {$endif}
  836. end;
  837. Var
  838. CThreadManager : TThreadManager;
  839. Procedure SetCThreadManager;
  840. begin
  841. With CThreadManager do begin
  842. InitManager :=@CInitThreads;
  843. DoneManager :=@CDoneThreads;
  844. BeginThread :=@CBeginThread;
  845. EndThread :=@CEndThread;
  846. SuspendThread :=@CSuspendThread;
  847. ResumeThread :=@CResumeThread;
  848. KillThread :=@CKillThread;
  849. ThreadSwitch :=@CThreadSwitch;
  850. CloseThread :=@CCloseThread;
  851. WaitForThreadTerminate :=@CWaitForThreadTerminate;
  852. ThreadSetPriority :=@CThreadSetPriority;
  853. ThreadGetPriority :=@CThreadGetPriority;
  854. GetCurrentThreadId :=@CGetCurrentThreadId;
  855. InitCriticalSection :=@CInitCriticalSection;
  856. DoneCriticalSection :=@CDoneCriticalSection;
  857. EnterCriticalSection :=@CEnterCriticalSection;
  858. TryEnterCriticalSection:=@CTryEnterCriticalSection;
  859. LeaveCriticalSection :=@CLeaveCriticalSection;
  860. InitThreadVar :=@CInitThreadVar;
  861. RelocateThreadVar :=@CRelocateThreadVar;
  862. AllocateThreadVars :=@CAllocateThreadVars;
  863. ReleaseThreadVars :=@CReleaseThreadVars;
  864. BasicEventCreate :=@intBasicEventCreate;
  865. BasicEventDestroy :=@intBasicEventDestroy;
  866. BasicEventResetEvent :=@intBasicEventResetEvent;
  867. BasicEventSetEvent :=@intBasicEventSetEvent;
  868. BasiceventWaitFor :=@intBasiceventWaitFor;
  869. rtlEventCreate :=@intrtlEventCreate;
  870. rtlEventDestroy :=@intrtlEventDestroy;
  871. rtlEventSetEvent :=@intrtlEventSetEvent;
  872. rtlEventResetEvent :=@intrtlEventResetEvent;
  873. rtleventWaitForTimeout :=@intrtleventWaitForTimeout;
  874. rtleventWaitFor :=@intrtleventWaitFor;
  875. // semaphores
  876. SemaphoreInit :=@cSemaphoreInit;
  877. SemaphoreDestroy :=@cSemaphoreDestroy;
  878. SemaphoreWait :=@cSemaphoreWait;
  879. SemaphorePost :=@cSemaphorePost;
  880. end;
  881. SetThreadManager(CThreadManager);
  882. end;
  883. initialization
  884. if ThreadingAlreadyUsed then
  885. begin
  886. writeln('Threading has been used before cthreads was initialized.');
  887. writeln('Make cthreads one of the first units in your uses clause.');
  888. runerror(211);
  889. end;
  890. SetCThreadManager;
  891. finalization
  892. end.