systhrds.pp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. {
  2. $Id$
  3. This file is part of the Free Pascal run time library.
  4. Copyright (c) 2002 by Peter Vreman,
  5. member of the Free Pascal development team.
  6. Linux (pthreads) threading support implementation
  7. See the file COPYING.FPC, included in this distribution,
  8. for details about the copyright.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  12. **********************************************************************}
  13. unit systhrds;
  14. interface
  15. {$S-}
  16. {$ifndef BSD}
  17. {$linklib c}
  18. {$linklib pthread}
  19. {$else}
  20. // Link reentrant libc with pthreads
  21. {$linklib c_r}
  22. {$endif}
  23. type
  24. PRTLCriticalSection = ^TRTLCriticalSection;
  25. TRTLCriticalSection = record
  26. m_spinlock : longint;
  27. m_count : longint;
  28. m_owner : pointer {pthread_t};
  29. m_kind : longint;
  30. m_waiting : record
  31. head,tail : pointer;
  32. end; {_pthread_queue}
  33. end;
  34. { Include generic thread interface }
  35. {$i threadh.inc}
  36. implementation
  37. Uses BaseUnix,unix;
  38. {*****************************************************************************
  39. Generic overloaded
  40. *****************************************************************************}
  41. { Include generic overloaded routines }
  42. {$i thread.inc}
  43. { Include OS specific parts. }
  44. {$i pthread.inc}
  45. {*****************************************************************************
  46. System dependent memory allocation
  47. *****************************************************************************}
  48. {
  49. {$ifndef BSD}
  50. Const
  51. { Constants for MMAP }
  52. MAP_PRIVATE =2;
  53. MAP_ANONYMOUS =$20;
  54. {$else}
  55. {$ifdef FreeBSD}
  56. CONST
  57. { Constants for MMAP. These are still private for *BSD }
  58. MAP_PRIVATE =2;
  59. MAP_ANONYMOUS =$1000;
  60. {$ELSE}
  61. {$ENTER ME}
  62. {$ENDIF}
  63. {$ENDIF}
  64. }
  65. {*****************************************************************************
  66. Threadvar support
  67. *****************************************************************************}
  68. {$ifdef HASTHREADVAR}
  69. const
  70. threadvarblocksize : dword = 0;
  71. var
  72. TLSKey : pthread_key_t;
  73. procedure SysInitThreadvar(var offset : dword;size : dword);
  74. begin
  75. offset:=threadvarblocksize;
  76. inc(threadvarblocksize,size);
  77. end;
  78. function SysRelocateThreadvar(offset : dword) : pointer;
  79. begin
  80. SysRelocateThreadvar:=pthread_getspecific(tlskey)+Offset;
  81. end;
  82. procedure SysAllocateThreadVars;
  83. var
  84. dataindex : pointer;
  85. begin
  86. { we've to allocate the memory from system }
  87. { because the FPC heap management uses }
  88. { exceptions which use threadvars but }
  89. { these aren't allocated yet ... }
  90. { allocate room on the heap for the thread vars }
  91. DataIndex:=Pointer(Fpmmap(0,threadvarblocksize,3,MAP_PRIVATE+MAP_ANONYMOUS,-1,0));
  92. FillChar(DataIndex^,threadvarblocksize,0);
  93. pthread_setspecific(tlskey,dataindex);
  94. end;
  95. procedure SysReleaseThreadVars;
  96. begin
  97. {$ifdef ver1_0}
  98. Fpmunmap(longint(pthread_getspecific(tlskey)),threadvarblocksize);
  99. {$else}
  100. Fpmunmap(pointer(pthread_getspecific(tlskey)),threadvarblocksize);
  101. {$endif}
  102. end;
  103. { Include OS independent Threadvar initialization }
  104. {$i threadvr.inc}
  105. {$endif HASTHREADVAR}
  106. {*****************************************************************************
  107. Thread starting
  108. *****************************************************************************}
  109. type
  110. pthreadinfo = ^tthreadinfo;
  111. tthreadinfo = record
  112. f : tthreadfunc;
  113. p : pointer;
  114. stklen : cardinal;
  115. end;
  116. procedure DoneThread;
  117. begin
  118. { Release Threadvars }
  119. {$ifdef HASTHREADVAR}
  120. SysReleaseThreadVars;
  121. {$endif HASTHREADVAR}
  122. end;
  123. function ThreadMain(param : pointer) : pointer;cdecl;
  124. var
  125. ti : tthreadinfo;
  126. {$ifdef DEBUG_MT}
  127. // in here, don't use write/writeln before having called
  128. // InitThread! I wonder if anyone ever debugged these routines,
  129. // because they will have crashed if DEBUG_MT was enabled!
  130. // this took me the good part of an hour to figure out
  131. // why it was crashing all the time!
  132. // this is kind of a workaround, we simply write(2) to fd 0
  133. s: string[100]; // not an ansistring
  134. {$endif DEBUG_MT}
  135. begin
  136. {$ifdef DEBUG_MT}
  137. s := 'New thread started, initing threadvars'#10;
  138. fpwrite(0,s[1],length(s));
  139. {$endif DEBUG_MT}
  140. {$ifdef HASTHREADVAR}
  141. { Allocate local thread vars, this must be the first thing,
  142. because the exception management and io depends on threadvars }
  143. SysAllocateThreadVars;
  144. {$endif HASTHREADVAR}
  145. { Copy parameter to local data }
  146. {$ifdef DEBUG_MT}
  147. s := 'New thread started, initialising ...'#10;
  148. fpwrite(0,s[1],length(s));
  149. {$endif DEBUG_MT}
  150. ti:=pthreadinfo(param)^;
  151. dispose(pthreadinfo(param));
  152. { Initialize thread }
  153. InitThread(ti.stklen);
  154. { Start thread function }
  155. {$ifdef DEBUG_MT}
  156. writeln('Jumping to thread function');
  157. {$endif DEBUG_MT}
  158. ThreadMain:=pointer(ti.f(ti.p));
  159. DoneThread;
  160. pthread_detach(pointer(pthread_self));
  161. end;
  162. function BeginThread(sa : Pointer;stacksize : dword;
  163. ThreadFunction : tthreadfunc;p : pointer;
  164. creationFlags : dword; var ThreadId : DWord) : DWord;
  165. var
  166. ti : pthreadinfo;
  167. thread_attr : pthread_attr_t;
  168. begin
  169. {$ifdef DEBUG_MT}
  170. writeln('Creating new thread');
  171. {$endif DEBUG_MT}
  172. { Initialize multithreading if not done }
  173. if not IsMultiThread then
  174. begin
  175. {$ifdef HASTHREADVAR}
  176. { We're still running in single thread mode, setup the TLS }
  177. pthread_key_create(@TLSKey,nil);
  178. InitThreadVars(@SysRelocateThreadvar);
  179. {$endif HASTHREADVAR}
  180. IsMultiThread:=true;
  181. end;
  182. { the only way to pass data to the newly created thread
  183. in a MT safe way, is to use the heap }
  184. new(ti);
  185. ti^.f:=ThreadFunction;
  186. ti^.p:=p;
  187. ti^.stklen:=stacksize;
  188. { call pthread_create }
  189. {$ifdef DEBUG_MT}
  190. writeln('Starting new thread');
  191. {$endif DEBUG_MT}
  192. pthread_attr_init(@thread_attr);
  193. pthread_attr_setinheritsched(@thread_attr, PTHREAD_EXPLICIT_SCHED);
  194. // will fail under linux -- apparently unimplemented
  195. pthread_attr_setscope(@thread_attr, PTHREAD_SCOPE_PROCESS);
  196. // don't create detached, we need to be able to join (waitfor) on
  197. // the newly created thread!
  198. //pthread_attr_setdetachstate(@thread_attr, PTHREAD_CREATE_DETACHED);
  199. if pthread_create(@threadid, @thread_attr, @ThreadMain,ti) <> 0 then begin
  200. threadid := 0;
  201. end;
  202. BeginThread:=threadid;
  203. {$ifdef DEBUG_MT}
  204. writeln('BeginThread returning ',BeginThread);
  205. {$endif DEBUG_MT}
  206. end;
  207. procedure EndThread(ExitCode : DWord);
  208. begin
  209. DoneThread;
  210. pthread_detach(pointer(pthread_self));
  211. pthread_exit(pointer(ExitCode));
  212. end;
  213. function SuspendThread (threadHandle : dword) : dword;
  214. begin
  215. {$Warning SuspendThread needs to be implemented}
  216. end;
  217. function ResumeThread (threadHandle : dword) : dword;
  218. begin
  219. {$Warning ResumeThread needs to be implemented}
  220. end;
  221. procedure ThreadSwitch; {give time to other threads}
  222. begin
  223. {extern int pthread_yield (void) __THROW;}
  224. {$Warning ThreadSwitch needs to be implemented}
  225. end;
  226. function KillThread (threadHandle : dword) : dword;
  227. begin
  228. pthread_detach(pointer(threadHandle));
  229. KillThread := pthread_cancel(Pointer(threadHandle));
  230. end;
  231. function WaitForThreadTerminate (threadHandle : dword; TimeoutMs : longint) : dword; {0=no timeout}
  232. var
  233. LResultP: Pointer;
  234. LResult: DWord;
  235. begin
  236. LResult := 0;
  237. LResultP := @LResult;
  238. pthread_join(Pointer(threadHandle), @LResultP);
  239. WaitForThreadTerminate := LResult;
  240. end;
  241. function ThreadSetPriority (threadHandle : dword; Prio: longint): boolean; {-15..+15, 0=normal}
  242. begin
  243. {$Warning ThreadSetPriority needs to be implemented}
  244. end;
  245. function ThreadGetPriority (threadHandle : dword): Integer;
  246. begin
  247. {$Warning ThreadGetPriority needs to be implemented}
  248. end;
  249. function GetCurrentThreadId : dword;
  250. begin
  251. GetCurrentThreadId:=dword(pthread_self);
  252. end;
  253. {*****************************************************************************
  254. Delphi/Win32 compatibility
  255. *****************************************************************************}
  256. procedure InitCriticalSection(var CS:TRTLCriticalSection);
  257. begin
  258. cs.m_spinlock:=0;
  259. cs.m_count:=0;
  260. cs.m_owner:=0;
  261. cs.m_kind:=1;
  262. cs.m_waiting.head:=0;
  263. cs.m_waiting.tail:=0;
  264. pthread_mutex_init(@CS,NIL);
  265. end;
  266. procedure EnterCriticalSection(var CS:TRTLCriticalSection);
  267. begin
  268. pthread_mutex_lock(@CS);
  269. end;
  270. procedure LeaveCriticalSection(var CS:TRTLCriticalSection);
  271. begin
  272. pthread_mutex_unlock(@CS);
  273. end;
  274. procedure DoneCriticalSection(var CS:TRTLCriticalSection);
  275. begin
  276. pthread_mutex_destroy(@CS);
  277. end;
  278. {*****************************************************************************
  279. Heap Mutex Protection
  280. *****************************************************************************}
  281. var
  282. HeapMutex : pthread_mutex_t;
  283. procedure PThreadHeapMutexInit;
  284. begin
  285. pthread_mutex_init(@heapmutex,nil);
  286. end;
  287. procedure PThreadHeapMutexDone;
  288. begin
  289. pthread_mutex_destroy(@heapmutex);
  290. end;
  291. procedure PThreadHeapMutexLock;
  292. begin
  293. pthread_mutex_lock(@heapmutex);
  294. end;
  295. procedure PThreadHeapMutexUnlock;
  296. begin
  297. pthread_mutex_unlock(@heapmutex);
  298. end;
  299. const
  300. PThreadMemoryMutexManager : TMemoryMutexManager = (
  301. MutexInit : @PThreadHeapMutexInit;
  302. MutexDone : @PThreadHeapMutexDone;
  303. MutexLock : @PThreadHeapMutexLock;
  304. MutexUnlock : @PThreadHeapMutexUnlock;
  305. );
  306. procedure InitHeapMutexes;
  307. begin
  308. SetMemoryMutexManager(PThreadMemoryMutexManager);
  309. end;
  310. initialization
  311. InitHeapMutexes;
  312. end.
  313. {
  314. $Log$
  315. Revision 1.20 2003-11-19 10:54:32 marco
  316. * some simple restructures
  317. Revision 1.19 2003/11/18 22:36:12 marco
  318. * Last patch was ok, problem was somewhere else. Moved *BSD part of pthreads to freebsd/pthreads.inc
  319. Revision 1.18 2003/11/18 22:35:09 marco
  320. * Last patch was ok, problem was somewhere else. Moved *BSD part of pthreads to freebsd/pthreads.inc
  321. Revision 1.17 2003/11/17 10:05:51 marco
  322. * threads for FreeBSD. Not working tho
  323. Revision 1.16 2003/11/17 08:27:50 marco
  324. * pthreads based ttread from Johannes Berg
  325. Revision 1.15 2003/10/01 21:00:09 peter
  326. * GetCurrentThreadHandle renamed to GetCurrentThreadId
  327. Revision 1.14 2003/10/01 20:53:08 peter
  328. * GetCurrentThreadId implemented
  329. Revision 1.13 2003/09/20 12:38:29 marco
  330. * FCL now compiles for FreeBSD with new 1.1. Now Linux.
  331. Revision 1.12 2003/09/16 13:17:03 marco
  332. * Wat cleanup, ouwe syscalls nu via baseunix e.d.
  333. Revision 1.11 2003/09/16 13:00:02 marco
  334. * small BSD gotcha removed (typing mmap params)
  335. Revision 1.10 2003/09/15 20:08:49 marco
  336. * small fixes. FreeBSD now cycles
  337. Revision 1.9 2003/09/14 20:15:01 marco
  338. * Unix reform stage two. Remove all calls from Unix that exist in Baseunix.
  339. Revision 1.8 2003/03/27 17:14:27 armin
  340. * more platform independent thread routines, needs to be implemented for unix
  341. Revision 1.7 2003/01/05 19:11:32 marco
  342. * small changes originating from introduction of Baseunix to FreeBSD
  343. Revision 1.6 2002/11/11 21:41:06 marco
  344. * syscall.inc -> syscallo.inc
  345. Revision 1.5 2002/10/31 13:45:21 carl
  346. * threadvar.inc -> threadvr.inc
  347. Revision 1.4 2002/10/26 18:27:52 marco
  348. * First series POSIX calls commits. Including getcwd.
  349. Revision 1.3 2002/10/18 18:05:06 marco
  350. * $I pthread.inc instead of pthreads.inc
  351. Revision 1.2 2002/10/18 12:19:59 marco
  352. * Fixes to get the generic *BSD RTL compiling again + fixes for thread
  353. support. Still problems left in fexpand. (inoutres?) Therefore fixed
  354. sysposix not yet commited
  355. Revision 1.1 2002/10/16 06:22:56 michael
  356. Threads renamed from threads to systhrds
  357. Revision 1.1 2002/10/14 19:39:17 peter
  358. * threads unit added for thread support
  359. }