cthreads.pp 31 KB

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