cthreads.pp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  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. end;
  276. function CResumeThread (threadHandle : TThreadID) : dword;
  277. begin
  278. // result := pthread_kill(threadHandle,SIGCONT);
  279. end;
  280. procedure sched_yield; cdecl; external 'c' name 'sched_yield';
  281. procedure CThreadSwitch; {give time to other threads}
  282. begin
  283. { At least on Mac OS X, the pthread_yield_np calls through to this. }
  284. { Further, sched_yield is in POSIX and supported on FreeBSD 4+, }
  285. { Linux, Mac OS X and Solaris, while the thread-specific yield }
  286. { routines are called differently everywhere and non-standard. }
  287. sched_yield;
  288. end;
  289. function CKillThread (threadHandle : TThreadID) : dword;
  290. begin
  291. pthread_detach(pthread_t(threadHandle));
  292. CKillThread := pthread_cancel(pthread_t(threadHandle));
  293. end;
  294. function CWaitForThreadTerminate (threadHandle : TThreadID; TimeoutMs : longint) : dword; {0=no timeout}
  295. var
  296. LResultP: Pointer;
  297. begin
  298. pthread_join(pthread_t(threadHandle), @LResultP);
  299. CWaitForThreadTerminate := dword(LResultP);
  300. end;
  301. function CThreadSetPriority (threadHandle : TThreadID; Prio: longint): boolean; {-15..+15, 0=normal}
  302. begin
  303. {$Warning ThreadSetPriority needs to be implemented}
  304. end;
  305. function CThreadGetPriority (threadHandle : TThreadID): Integer;
  306. begin
  307. {$Warning ThreadGetPriority needs to be implemented}
  308. end;
  309. function CGetCurrentThreadId : TThreadID;
  310. begin
  311. CGetCurrentThreadId := TThreadID (pthread_self());
  312. end;
  313. {*****************************************************************************
  314. Delphi/Win32 compatibility
  315. *****************************************************************************}
  316. procedure CInitCriticalSection(var CS);
  317. var
  318. MAttr : pthread_mutexattr_t;
  319. res: longint;
  320. begin
  321. res:=pthread_mutexattr_init(@MAttr);
  322. if res=0 then
  323. begin
  324. res:=pthread_mutexattr_settype(@MAttr,longint(_PTHREAD_MUTEX_RECURSIVE));
  325. if res=0 then
  326. res := pthread_mutex_init(@CS,@MAttr)
  327. else
  328. { No recursive mutex support :/ }
  329. res := pthread_mutex_init(@CS,NIL);
  330. end
  331. else
  332. res:= pthread_mutex_init(@CS,NIL);
  333. pthread_mutexattr_destroy(@MAttr);
  334. if res <> 0 then
  335. fpc_threaderror;
  336. end;
  337. procedure CEnterCriticalSection(var CS);
  338. begin
  339. if pthread_mutex_lock(@CS) <> 0 then
  340. fpc_threaderror
  341. end;
  342. procedure CLeaveCriticalSection(var CS);
  343. begin
  344. if pthread_mutex_unlock(@CS) <> 0 then
  345. fpc_threaderror
  346. end;
  347. procedure CDoneCriticalSection(var CS);
  348. begin
  349. { unlock as long as unlocking works to unlock it if it is recursive
  350. some Delphi code might call this function with a locked mutex }
  351. while pthread_mutex_unlock(@CS)=0 do
  352. ;
  353. if pthread_mutex_destroy(@CS) <> 0 then
  354. fpc_threaderror;
  355. end;
  356. {*****************************************************************************
  357. Semaphore routines
  358. *****************************************************************************}
  359. procedure cSemaphoreWait(const FSem: Pointer);
  360. var
  361. res: cint;
  362. err: cint;
  363. {$if not defined(has_sem_init) and not defined(has_sem_open)}
  364. b: byte;
  365. {$endif}
  366. begin
  367. {$if defined(has_sem_init) or defined(has_sem_open)}
  368. repeat
  369. res:=sem_wait(PSemaphore(FSem));
  370. err:=fpgetCerrno;
  371. until (res<>-1) or (err<>ESysEINTR);
  372. {$else}
  373. repeat
  374. res:=fpread(PFilDes(FSem)^[0], b, 1);
  375. err:=fpgeterrno;
  376. until (res<>-1) or ((err<>ESysEINTR) and (err<>ESysEAgain));
  377. {$endif}
  378. end;
  379. {$if defined(has_sem_timedwait)}
  380. function cSemaphoreTimedWait(const FSem: Pointer; const Timeout: ttimespec): cint;
  381. var
  382. res: cint;
  383. err: cint;
  384. begin
  385. repeat
  386. res:=sem_timedwait(PSemaphore(FSem), @Timeout);
  387. if res=0 then exit(0);
  388. err:=fpgetCerrno;
  389. until err<>ESysEINTR;
  390. result:=err;
  391. end;
  392. {$endif}
  393. procedure cSemaphorePost(const FSem: Pointer);
  394. {$if defined(has_sem_init) or defined(has_sem_open)}
  395. begin
  396. sem_post(PSemaphore(FSem));
  397. end;
  398. {$else}
  399. var
  400. writeres: cint;
  401. err: cint;
  402. b : byte;
  403. begin
  404. b:=0;
  405. repeat
  406. writeres:=fpwrite(PFilDes(FSem)^[1], b, 1);
  407. err:=fpgeterrno;
  408. until (writeres<>-1) or ((err<>ESysEINTR) and (err<>ESysEAgain));
  409. end;
  410. {$endif}
  411. function cSemaphoreTryWait(const FSem: pointer): TTryWaitResult;
  412. var
  413. res: cint;
  414. err: cint;
  415. {$if defined(has_sem_init) or defined(has_sem_open)}
  416. begin
  417. repeat
  418. res:=sem_trywait(FSem);
  419. err:=fpgetCerrno;
  420. until (res<>-1) or (err<>ESysEINTR);
  421. if (res=0) then
  422. result:=tw_semwasunlocked
  423. else if (err=ESysEAgain) then
  424. result:=tw_semwaslocked
  425. else
  426. result:=tw_error;
  427. {$else has_sem_init or has_sem_open}
  428. var
  429. fds: TFDSet;
  430. tv : timeval;
  431. begin
  432. tv.tv_sec:=0;
  433. tv.tv_usec:=0;
  434. fpFD_ZERO(fds);
  435. fpFD_SET(PFilDes(FSem)^[0],fds);
  436. repeat
  437. res:=fpselect(PFilDes(FSem)^[0]+1,@fds,nil,nil,@tv);
  438. err:=fpgeterrno;
  439. until (res>=0) or ((res=-1) and (err<>ESysEIntr));
  440. if (res>0) then
  441. begin
  442. cSemaphoreWait(FSem);
  443. result:=tw_semwasunlocked
  444. end
  445. else if (res=0) then
  446. result:=tw_semwaslocked
  447. else
  448. result:=tw_error;
  449. {$endif has_sem_init or has_sem_open}
  450. end;
  451. {$if defined(has_sem_open) and not defined(has_sem_init)}
  452. function cIntSemaphoreOpen(const name: pchar; initvalue: boolean): Pointer;
  453. var
  454. err: cint;
  455. begin
  456. repeat
  457. cIntSemaphoreOpen := sem_open(name,O_CREAT,0,ord(initvalue));
  458. err:=fpgetCerrno;
  459. until (ptrint(cIntSemaphoreOpen) <> SEM_FAILED) or (err <> ESysEINTR);
  460. if (ptrint(cIntSemaphoreOpen) <> SEM_FAILED) then
  461. { immediately unlink so the semaphore will be destroyed when the }
  462. { the process exits }
  463. sem_unlink(name)
  464. else
  465. cIntSemaphoreOpen:=NIL;
  466. end;
  467. {$endif}
  468. function cIntSemaphoreInit(initvalue: boolean): Pointer;
  469. {$if defined(has_sem_open) and not defined(has_sem_init)}
  470. var
  471. tid: string[31];
  472. semname: string[63];
  473. {$endif}
  474. begin
  475. {$ifdef has_sem_init}
  476. cIntSemaphoreInit := GetMem(SizeOf(TSemaphore));
  477. if sem_init(PSemaphore(cIntSemaphoreInit), 0, ord(initvalue)) <> 0 then
  478. begin
  479. FreeMem(cIntSemaphoreInit);
  480. cIntSemaphoreInit:=NIL;
  481. end;
  482. {$else}
  483. {$ifdef has_sem_open}
  484. { avoid a potential temporary nameclash with another process/thread }
  485. str(fpGetPid,semname);
  486. str(ptruint(pthread_self),tid);
  487. semname:='/FPC'+semname+'T'+tid+#0;
  488. cIntSemaphoreInit:=cIntSemaphoreOpen(@semname[1],initvalue);
  489. {$else}
  490. cIntSemaphoreInit := GetMem(SizeOf(TFilDes));
  491. if (fppipe(PFilDes(cIntSemaphoreInit)^) <> 0) then
  492. begin
  493. FreeMem(cIntSemaphoreInit);
  494. cIntSemaphoreInit:=nil;
  495. end
  496. else if initvalue then
  497. cSemaphorePost(cIntSemaphoreInit);
  498. {$endif}
  499. {$endif}
  500. end;
  501. function cSemaphoreInit: Pointer;
  502. begin
  503. cSemaphoreInit:=cIntSemaphoreInit(false);
  504. end;
  505. procedure cSemaphoreDestroy(const FSem: Pointer);
  506. begin
  507. {$ifdef has_sem_init}
  508. sem_destroy(PSemaphore(FSem));
  509. FreeMem(FSem);
  510. {$else}
  511. {$ifdef has_sem_open}
  512. sem_close(PSemaphore(FSem));
  513. {$else has_sem_init}
  514. fpclose(PFilDes(FSem)^[0]);
  515. fpclose(PFilDes(FSem)^[1]);
  516. FreeMem(FSem);
  517. {$endif}
  518. {$endif}
  519. end;
  520. type
  521. TPthreadCondition = pthread_cond_t;
  522. TPthreadMutex = pthread_mutex_t;
  523. Tbasiceventstate=record
  524. FCondVar: TPthreadCondition;
  525. FEventSection: TPthreadMutex;
  526. FWaiters: longint;
  527. FIsSet,
  528. FManualReset,
  529. FDestroying : Boolean;
  530. end;
  531. plocaleventstate = ^tbasiceventstate;
  532. // peventstate=pointer;
  533. Const
  534. wrSignaled = 0;
  535. wrTimeout = 1;
  536. wrAbandoned= 2;
  537. wrError = 3;
  538. function IntBasicEventCreate(EventAttributes : Pointer; AManualReset,InitialState : Boolean;const Name : ansistring):pEventState;
  539. var
  540. MAttr : pthread_mutexattr_t;
  541. res : cint;
  542. begin
  543. new(plocaleventstate(result));
  544. plocaleventstate(result)^.FManualReset:=AManualReset;
  545. plocaleventstate(result)^.FWaiters:=0;
  546. plocaleventstate(result)^.FDestroying:=False;
  547. plocaleventstate(result)^.FIsSet:=InitialState;
  548. res := pthread_cond_init(@plocaleventstate(result)^.FCondVar, nil);
  549. if (res <> 0) then
  550. begin
  551. FreeMem(result);
  552. fpc_threaderror;
  553. end;
  554. res:=pthread_mutexattr_init(@MAttr);
  555. if res=0 then
  556. begin
  557. res:=pthread_mutexattr_settype(@MAttr,longint(_PTHREAD_MUTEX_RECURSIVE));
  558. if Res=0 then
  559. Res:=pthread_mutex_init(@plocaleventstate(result)^.feventsection,@MAttr)
  560. else
  561. res:=pthread_mutex_init(@plocaleventstate(result)^.feventsection,nil);
  562. end
  563. else
  564. res:=pthread_mutex_init(@plocaleventstate(result)^.feventsection,nil);
  565. pthread_mutexattr_destroy(@MAttr);
  566. if res <> 0 then
  567. begin
  568. pthread_cond_destroy(@plocaleventstate(result)^.FCondVar);
  569. FreeMem(result);
  570. fpc_threaderror;
  571. end;
  572. end;
  573. procedure Intbasiceventdestroy(state:peventstate);
  574. begin
  575. { safely mark that we are destroying this event }
  576. pthread_mutex_lock(@plocaleventstate(state)^.feventsection);
  577. plocaleventstate(state)^.FDestroying:=true;
  578. { send a signal to all threads that are waiting }
  579. pthread_cond_broadcast(@plocaleventstate(state)^.FCondVar);
  580. pthread_mutex_unlock(@plocaleventstate(state)^.feventsection);
  581. { now wait until they've finished their business }
  582. while (plocaleventstate(state)^.FWaiters <> 0) do
  583. cThreadSwitch;
  584. { and clean up }
  585. pthread_cond_destroy(@plocaleventstate(state)^.Fcondvar);
  586. pthread_mutex_destroy(@plocaleventstate(state)^.FEventSection);
  587. dispose(plocaleventstate(state));
  588. end;
  589. procedure IntbasiceventResetEvent(state:peventstate);
  590. begin
  591. pthread_mutex_lock(@plocaleventstate(state)^.feventsection);
  592. plocaleventstate(state)^.fisset:=false;
  593. pthread_mutex_unlock(@plocaleventstate(state)^.feventsection);
  594. end;
  595. procedure IntbasiceventSetEvent(state:peventstate);
  596. begin
  597. pthread_mutex_lock(@plocaleventstate(state)^.feventsection);
  598. Try
  599. plocaleventstate(state)^.Fisset:=true;
  600. if not(plocaleventstate(state)^.FManualReset) then
  601. pthread_cond_signal(@plocaleventstate(state)^.Fcondvar)
  602. else
  603. pthread_cond_broadcast(@plocaleventstate(state)^.Fcondvar);
  604. finally
  605. pthread_mutex_unlock(@plocaleventstate(state)^.feventsection);
  606. end;
  607. end;
  608. function IntbasiceventWaitFor(Timeout : Cardinal;state:peventstate) : longint;
  609. var
  610. timespec: ttimespec;
  611. errres: cint;
  612. isset: boolean;
  613. tnow : timeval;
  614. begin
  615. { safely check whether we are being destroyed, if so immediately return. }
  616. { otherwise (under the same mutex) increase the number of waiters }
  617. pthread_mutex_lock(@plocaleventstate(state)^.feventsection);
  618. if (plocaleventstate(state)^.FDestroying) then
  619. begin
  620. pthread_mutex_unlock(@plocaleventstate(state)^.feventsection);
  621. result := wrAbandoned;
  622. exit;
  623. end;
  624. { not a regular inc() because it may happen simulatneously with the }
  625. { interlockeddecrement() at the end }
  626. interlockedincrement(plocaleventstate(state)^.FWaiters);
  627. //Wait without timeout using pthread_cond_wait
  628. if Timeout = $FFFFFFFF then
  629. begin
  630. while (not plocaleventstate(state)^.FIsSet) and (not plocaleventstate(state)^.FDestroying) do
  631. pthread_cond_wait(@plocaleventstate(state)^.Fcondvar, @plocaleventstate(state)^.feventsection);
  632. end
  633. else
  634. begin
  635. //Wait with timeout using pthread_cont_timedwait
  636. fpgettimeofday(@tnow,nil);
  637. timespec.tv_sec := tnow.tv_sec + (clong(timeout) div 1000);
  638. timespec.tv_nsec := (clong(timeout) mod 1000)*1000000 + tnow.tv_usec*1000;
  639. if timespec.tv_nsec >= 1000000000 then
  640. begin
  641. inc(timespec.tv_sec);
  642. dec(timespec.tv_nsec, 1000000000);
  643. end;
  644. errres:=0;
  645. while (not plocaleventstate(state)^.FDestroying) and (not plocaleventstate(state)^.FIsSet) and (errres<>ESysETIMEDOUT) do
  646. errres:=pthread_cond_timedwait(@plocaleventstate(state)^.Fcondvar, @plocaleventstate(state)^.feventsection, @timespec);
  647. end;
  648. isset := plocaleventstate(state)^.FIsSet;
  649. { if ManualReset=false, reset the event immediately. }
  650. if (plocaleventstate(state)^.FManualReset=false) then
  651. plocaleventstate(state)^.FIsSet := false;
  652. //check the results...
  653. if plocaleventstate(state)^.FDestroying then
  654. Result := wrAbandoned
  655. else
  656. if IsSet then
  657. Result := wrSignaled
  658. else
  659. begin
  660. if errres=ESysETIMEDOUT then
  661. Result := wrTimeout
  662. else
  663. Result := wrError;
  664. end;
  665. pthread_mutex_unlock(@plocaleventstate(state)^.feventsection);
  666. { don't put this above the previous pthread_mutex_unlock, because }
  667. { otherwise we can get errors in case an object is destroyed between }
  668. { end of the wait/sleep loop and the signalling above. }
  669. { The pthread_mutex_unlock above takes care of the memory barrier }
  670. interlockeddecrement(plocaleventstate(state)^.FWaiters);
  671. end;
  672. function intRTLEventCreate: PRTLEvent;
  673. var p:pintrtlevent;
  674. begin
  675. new(p);
  676. pthread_cond_init(@p^.condvar, nil);
  677. pthread_mutex_init(@p^.mutex, nil);
  678. p^.isset:=false;
  679. result:=PRTLEVENT(p);
  680. end;
  681. procedure intRTLEventDestroy(AEvent: PRTLEvent);
  682. var p:pintrtlevent;
  683. begin
  684. p:=pintrtlevent(aevent);
  685. pthread_cond_destroy(@p^.condvar);
  686. pthread_mutex_destroy(@p^.mutex);
  687. dispose(p);
  688. end;
  689. procedure intRTLEventSetEvent(AEvent: PRTLEvent);
  690. var p:pintrtlevent;
  691. begin
  692. p:=pintrtlevent(aevent);
  693. pthread_mutex_lock(@p^.mutex);
  694. p^.isset:=true;
  695. pthread_cond_signal(@p^.condvar);
  696. pthread_mutex_unlock(@p^.mutex);
  697. end;
  698. procedure intRTLEventResetEvent(AEvent: PRTLEvent);
  699. var p:pintrtlevent;
  700. begin
  701. p:=pintrtlevent(aevent);
  702. pthread_mutex_lock(@p^.mutex);
  703. p^.isset:=false;
  704. pthread_mutex_unlock(@p^.mutex);
  705. end;
  706. procedure intRTLEventWaitFor(AEvent: PRTLEvent);
  707. var p:pintrtlevent;
  708. begin
  709. p:=pintrtlevent(aevent);
  710. pthread_mutex_lock(@p^.mutex);
  711. while not p^.isset do pthread_cond_wait(@p^.condvar, @p^.mutex);
  712. p^.isset:=false;
  713. pthread_mutex_unlock(@p^.mutex);
  714. end;
  715. procedure intRTLEventWaitForTimeout(AEvent: PRTLEvent;timeout : longint);
  716. var
  717. p : pintrtlevent;
  718. errres : cint;
  719. timespec : ttimespec;
  720. tnow : timeval;
  721. begin
  722. p:=pintrtlevent(aevent);
  723. fpgettimeofday(@tnow,nil);
  724. timespec.tv_sec:=tnow.tv_sec+(timeout div 1000);
  725. timespec.tv_nsec:=(timeout mod 1000)*1000000 + tnow.tv_usec*1000;
  726. if timespec.tv_nsec >= 1000000000 then
  727. begin
  728. inc(timespec.tv_sec);
  729. dec(timespec.tv_nsec, 1000000000);
  730. end;
  731. errres:=0;
  732. pthread_mutex_lock(@p^.mutex);
  733. while (not p^.isset) and
  734. (errres <> ESysETIMEDOUT) do
  735. begin
  736. errres:=pthread_cond_timedwait(@p^.condvar, @p^.mutex, @timespec);
  737. end;
  738. p^.isset:=false;
  739. pthread_mutex_unlock(@p^.mutex);
  740. end;
  741. type
  742. threadmethod = procedure of object;
  743. Function CInitThreads : Boolean;
  744. begin
  745. {$ifdef DEBUG_MT}
  746. Writeln('Entering InitThreads.');
  747. {$endif}
  748. {$ifndef dynpthreads}
  749. Result:=True;
  750. {$else}
  751. Result:=LoadPthreads;
  752. {$endif}
  753. ThreadID := TThreadID (pthread_self);
  754. {$ifdef DEBUG_MT}
  755. Writeln('InitThreads : ',Result);
  756. {$endif DEBUG_MT}
  757. end;
  758. Function CDoneThreads : Boolean;
  759. begin
  760. {$ifndef dynpthreads}
  761. Result:=True;
  762. {$else}
  763. Result:=UnloadPthreads;
  764. {$endif}
  765. end;
  766. Var
  767. CThreadManager : TThreadManager;
  768. Procedure SetCThreadManager;
  769. begin
  770. With CThreadManager do begin
  771. InitManager :=@CInitThreads;
  772. DoneManager :=@CDoneThreads;
  773. BeginThread :=@CBeginThread;
  774. EndThread :=@CEndThread;
  775. SuspendThread :=@CSuspendThread;
  776. ResumeThread :=@CResumeThread;
  777. KillThread :=@CKillThread;
  778. ThreadSwitch :=@CThreadSwitch;
  779. WaitForThreadTerminate :=@CWaitForThreadTerminate;
  780. ThreadSetPriority :=@CThreadSetPriority;
  781. ThreadGetPriority :=@CThreadGetPriority;
  782. GetCurrentThreadId :=@CGetCurrentThreadId;
  783. InitCriticalSection :=@CInitCriticalSection;
  784. DoneCriticalSection :=@CDoneCriticalSection;
  785. EnterCriticalSection :=@CEnterCriticalSection;
  786. LeaveCriticalSection :=@CLeaveCriticalSection;
  787. InitThreadVar :=@CInitThreadVar;
  788. RelocateThreadVar :=@CRelocateThreadVar;
  789. AllocateThreadVars :=@CAllocateThreadVars;
  790. ReleaseThreadVars :=@CReleaseThreadVars;
  791. BasicEventCreate :=@intBasicEventCreate;
  792. BasicEventDestroy :=@intBasicEventDestroy;
  793. BasicEventResetEvent :=@intBasicEventResetEvent;
  794. BasicEventSetEvent :=@intBasicEventSetEvent;
  795. BasiceventWaitFor :=@intBasiceventWaitFor;
  796. rtlEventCreate :=@intrtlEventCreate;
  797. rtlEventDestroy :=@intrtlEventDestroy;
  798. rtlEventSetEvent :=@intrtlEventSetEvent;
  799. rtlEventResetEvent :=@intrtlEventResetEvent;
  800. rtleventWaitForTimeout :=@intrtleventWaitForTimeout;
  801. rtleventWaitFor :=@intrtleventWaitFor;
  802. // semaphores
  803. SemaphoreInit :=@cSemaphoreInit;
  804. SemaphoreDestroy :=@cSemaphoreDestroy;
  805. SemaphoreWait :=@cSemaphoreWait;
  806. SemaphorePost :=@cSemaphorePost;
  807. end;
  808. SetThreadManager(CThreadManager);
  809. end;
  810. initialization
  811. if ThreadingAlreadyUsed then
  812. begin
  813. writeln('Threading has been used before cthreads was initialized.');
  814. writeln('Make cthreads one of the first units in your uses clause.');
  815. runerror(211);
  816. end;
  817. SetCThreadManager;
  818. finalization
  819. end.