cthreads.pp 23 KB

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