cthreads.pp 28 KB

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