cthreads.pp 31 KB

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