cthreads.pp 31 KB

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