cthreads.pp 31 KB

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