cthreads.pp 27 KB

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