threads.c 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761
  1. /* Copyright (C) 1995,1996,1997,1998,2000,2001, 2002, 2003, 2004, 2005, 2006, 2008 Free Software Foundation, Inc.
  2. *
  3. * This library is free software; you can redistribute it and/or
  4. * modify it under the terms of the GNU Lesser General Public
  5. * License as published by the Free Software Foundation; either
  6. * version 2.1 of the License, or (at your option) any later version.
  7. *
  8. * This library 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. See the GNU
  11. * Lesser General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU Lesser General Public
  14. * License along with this library; if not, write to the Free Software
  15. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  16. */
  17. #ifdef HAVE_CONFIG_H
  18. # include <config.h>
  19. #endif
  20. #include "libguile/_scm.h"
  21. #if HAVE_UNISTD_H
  22. #include <unistd.h>
  23. #endif
  24. #include <stdio.h>
  25. #include <assert.h>
  26. #ifdef HAVE_STRING_H
  27. #include <string.h> /* for memset used by FD_ZERO on Solaris 10 */
  28. #endif
  29. #if HAVE_SYS_TIME_H
  30. #include <sys/time.h>
  31. #endif
  32. #include "libguile/validate.h"
  33. #include "libguile/root.h"
  34. #include "libguile/eval.h"
  35. #include "libguile/async.h"
  36. #include "libguile/ports.h"
  37. #include "libguile/threads.h"
  38. #include "libguile/dynwind.h"
  39. #include "libguile/iselect.h"
  40. #include "libguile/fluids.h"
  41. #include "libguile/continuations.h"
  42. #include "libguile/gc.h"
  43. #include "libguile/init.h"
  44. #ifdef __MINGW32__
  45. #ifndef ETIMEDOUT
  46. # define ETIMEDOUT WSAETIMEDOUT
  47. #endif
  48. # include <fcntl.h>
  49. # include <process.h>
  50. # define pipe(fd) _pipe (fd, 256, O_BINARY)
  51. #endif /* __MINGW32__ */
  52. /*** Queues */
  53. /* Make an empty queue data structure.
  54. */
  55. static SCM
  56. make_queue ()
  57. {
  58. return scm_cons (SCM_EOL, SCM_EOL);
  59. }
  60. /* Put T at the back of Q and return a handle that can be used with
  61. remqueue to remove T from Q again.
  62. */
  63. static SCM
  64. enqueue (SCM q, SCM t)
  65. {
  66. SCM c = scm_cons (t, SCM_EOL);
  67. if (scm_is_null (SCM_CDR (q)))
  68. SCM_SETCDR (q, c);
  69. else
  70. SCM_SETCDR (SCM_CAR (q), c);
  71. SCM_SETCAR (q, c);
  72. return c;
  73. }
  74. /* Remove the element that the handle C refers to from the queue Q. C
  75. must have been returned from a call to enqueue. The return value
  76. is zero when the element referred to by C has already been removed.
  77. Otherwise, 1 is returned.
  78. */
  79. static int
  80. remqueue (SCM q, SCM c)
  81. {
  82. SCM p, prev = q;
  83. for (p = SCM_CDR (q); !scm_is_null (p); p = SCM_CDR (p))
  84. {
  85. if (scm_is_eq (p, c))
  86. {
  87. if (scm_is_eq (c, SCM_CAR (q)))
  88. SCM_SETCAR (q, SCM_CDR (c));
  89. SCM_SETCDR (prev, SCM_CDR (c));
  90. return 1;
  91. }
  92. prev = p;
  93. }
  94. return 0;
  95. }
  96. /* Remove the front-most element from the queue Q and return it.
  97. Return SCM_BOOL_F when Q is empty.
  98. */
  99. static SCM
  100. dequeue (SCM q)
  101. {
  102. SCM c = SCM_CDR (q);
  103. if (scm_is_null (c))
  104. return SCM_BOOL_F;
  105. else
  106. {
  107. SCM_SETCDR (q, SCM_CDR (c));
  108. if (scm_is_null (SCM_CDR (q)))
  109. SCM_SETCAR (q, SCM_EOL);
  110. return SCM_CAR (c);
  111. }
  112. }
  113. /*** Thread smob routines */
  114. static SCM
  115. thread_mark (SCM obj)
  116. {
  117. scm_i_thread *t = SCM_I_THREAD_DATA (obj);
  118. scm_gc_mark (t->result);
  119. scm_gc_mark (t->join_queue);
  120. scm_gc_mark (t->dynwinds);
  121. scm_gc_mark (t->active_asyncs);
  122. scm_gc_mark (t->continuation_root);
  123. return t->dynamic_state;
  124. }
  125. static int
  126. thread_print (SCM exp, SCM port, scm_print_state *pstate SCM_UNUSED)
  127. {
  128. /* On a Gnu system pthread_t is an unsigned long, but on mingw it's a
  129. struct. A cast like "(unsigned long) t->pthread" is a syntax error in
  130. the struct case, hence we go via a union, and extract according to the
  131. size of pthread_t. */
  132. union {
  133. scm_i_pthread_t p;
  134. unsigned short us;
  135. unsigned int ui;
  136. unsigned long ul;
  137. scm_t_uintmax um;
  138. } u;
  139. scm_i_thread *t = SCM_I_THREAD_DATA (exp);
  140. scm_i_pthread_t p = t->pthread;
  141. scm_t_uintmax id;
  142. u.p = p;
  143. if (sizeof (p) == sizeof (unsigned short))
  144. id = u.us;
  145. else if (sizeof (p) == sizeof (unsigned int))
  146. id = u.ui;
  147. else if (sizeof (p) == sizeof (unsigned long))
  148. id = u.ul;
  149. else
  150. id = u.um;
  151. scm_puts ("#<thread ", port);
  152. scm_uintprint (id, 10, port);
  153. scm_puts (" (", port);
  154. scm_uintprint ((scm_t_bits)t, 16, port);
  155. scm_puts (")>", port);
  156. return 1;
  157. }
  158. static size_t
  159. thread_free (SCM obj)
  160. {
  161. scm_i_thread *t = SCM_I_THREAD_DATA (obj);
  162. assert (t->exited);
  163. scm_gc_free (t, sizeof (*t), "thread");
  164. return 0;
  165. }
  166. /*** Blocking on queues. */
  167. /* See also scm_i_queue_async_cell for how such a block is
  168. interrputed.
  169. */
  170. /* Put the current thread on QUEUE and go to sleep, waiting for it to
  171. be woken up by a call to 'unblock_from_queue', or to be
  172. interrupted. Upon return of this function, the current thread is
  173. no longer on QUEUE, even when the sleep has been interrupted.
  174. The QUEUE data structure is assumed to be protected by MUTEX and
  175. the caller of block_self must hold MUTEX. It will be atomically
  176. unlocked while sleeping, just as with scm_i_pthread_cond_wait.
  177. SLEEP_OBJECT is an arbitrary SCM value that is kept alive as long
  178. as MUTEX is needed.
  179. When WAITTIME is not NULL, the sleep will be aborted at that time.
  180. The return value of block_self is an errno value. It will be zero
  181. when the sleep has been successfully completed by a call to
  182. unblock_from_queue, EINTR when it has been interrupted by the
  183. delivery of a system async, and ETIMEDOUT when the timeout has
  184. expired.
  185. The system asyncs themselves are not executed by block_self.
  186. */
  187. static int
  188. block_self (SCM queue, SCM sleep_object, scm_i_pthread_mutex_t *mutex,
  189. const scm_t_timespec *waittime)
  190. {
  191. scm_i_thread *t = SCM_I_CURRENT_THREAD;
  192. SCM q_handle;
  193. int err;
  194. if (scm_i_setup_sleep (t, sleep_object, mutex, -1))
  195. err = EINTR;
  196. else
  197. {
  198. t->block_asyncs++;
  199. q_handle = enqueue (queue, t->handle);
  200. if (waittime == NULL)
  201. err = scm_i_scm_pthread_cond_wait (&t->sleep_cond, mutex);
  202. else
  203. err = scm_i_scm_pthread_cond_timedwait (&t->sleep_cond, mutex, waittime);
  204. /* When we are still on QUEUE, we have been interrupted. We
  205. report this only when no other error (such as a timeout) has
  206. happened above.
  207. */
  208. if (remqueue (queue, q_handle) && err == 0)
  209. err = EINTR;
  210. t->block_asyncs--;
  211. scm_i_reset_sleep (t);
  212. }
  213. return err;
  214. }
  215. /* Wake up the first thread on QUEUE, if any. The caller must hold
  216. the mutex that protects QUEUE. The awoken thread is returned, or
  217. #f when the queue was empty.
  218. */
  219. static SCM
  220. unblock_from_queue (SCM queue)
  221. {
  222. SCM thread = dequeue (queue);
  223. if (scm_is_true (thread))
  224. scm_i_pthread_cond_signal (&SCM_I_THREAD_DATA(thread)->sleep_cond);
  225. return thread;
  226. }
  227. /* Getting into and out of guile mode.
  228. */
  229. /* Ken Raeburn observes that the implementation of suspend and resume
  230. (and the things that build on top of them) are very likely not
  231. correct (see below). We will need fix this eventually, and that's
  232. why scm_leave_guile/scm_enter_guile are not exported in the API.
  233. Ken writes:
  234. Consider this sequence:
  235. Function foo, called in Guile mode, calls suspend (maybe indirectly
  236. through scm_leave_guile), which does this:
  237. // record top of stack for the GC
  238. t->top = SCM_STACK_PTR (&t); // just takes address of automatic
  239. var 't'
  240. // save registers.
  241. SCM_FLUSH_REGISTER_WINDOWS; // sparc only
  242. setjmp (t->regs); // here's most of the magic
  243. ... and returns.
  244. Function foo has a SCM value X, a handle on a non-immediate object, in
  245. a caller-saved register R, and it's the only reference to the object
  246. currently.
  247. The compiler wants to use R in suspend, so it pushes the current
  248. value, X, into a stack slot which will be reloaded on exit from
  249. suspend; then it loads stuff into R and goes about its business. The
  250. setjmp call saves (some of) the current registers, including R, which
  251. no longer contains X. (This isn't a problem for a normal
  252. setjmp/longjmp situation, where longjmp would be called before
  253. setjmp's caller returns; the old value for X would be loaded back from
  254. the stack after the longjmp, before the function returned.)
  255. So, suspend returns, loading X back into R (and invalidating the jump
  256. buffer) in the process. The caller foo then goes off and calls a
  257. bunch of other functions out of Guile mode, occasionally storing X on
  258. the stack again, but, say, much deeper on the stack than suspend's
  259. stack frame went, and the stack slot where suspend had written X has
  260. long since been overwritten with other values.
  261. Okay, nothing actively broken so far. Now, let garbage collection
  262. run, triggered by another thread.
  263. The thread calling foo is out of Guile mode at the time, so the
  264. garbage collector just scans a range of stack addresses. Too bad that
  265. X isn't stored there. So the pointed-to storage goes onto the free
  266. list, and I think you can see where things go from there.
  267. Is there anything I'm missing that'll prevent this scenario from
  268. happening? I mean, aside from, "well, suspend and scm_leave_guile
  269. don't have many local variables, so they probably won't need to save
  270. any registers on most systems, so we hope everything will wind up in
  271. the jump buffer and we'll just get away with it"?
  272. (And, going the other direction, if scm_leave_guile and suspend push
  273. the stack pointer over onto a new page, and foo doesn't make further
  274. function calls and thus the stack pointer no longer includes that
  275. page, are we guaranteed that the kernel cannot release the now-unused
  276. stack page that contains the top-of-stack pointer we just saved? I
  277. don't know if any OS actually does that. If it does, we could get
  278. faults in garbage collection.)
  279. I don't think scm_without_guile has to have this problem, as it gets
  280. more control over the stack handling -- but it should call setjmp
  281. itself. I'd probably try something like:
  282. // record top of stack for the GC
  283. t->top = SCM_STACK_PTR (&t);
  284. // save registers.
  285. SCM_FLUSH_REGISTER_WINDOWS;
  286. setjmp (t->regs);
  287. res = func(data);
  288. scm_enter_guile (t);
  289. ... though even that's making some assumptions about the stack
  290. ordering of local variables versus caller-saved registers.
  291. For something like scm_leave_guile to work, I don't think it can just
  292. rely on invalidated jump buffers. A valid jump buffer, and a handle
  293. on the stack state at the point when the jump buffer was initialized,
  294. together, would work fine, but I think then we're talking about macros
  295. invoking setjmp in the caller's stack frame, and requiring that the
  296. caller of scm_leave_guile also call scm_enter_guile before returning,
  297. kind of like pthread_cleanup_push/pop calls that have to be paired up
  298. in a function. (In fact, the pthread ones have to be paired up
  299. syntactically, as if they might expand to a compound statement
  300. incorporating the user's code, and invoking a compiler's
  301. exception-handling primitives. Which might be something to think
  302. about for cases where Guile is used with C++ exceptions or
  303. pthread_cancel.)
  304. */
  305. scm_i_pthread_key_t scm_i_thread_key;
  306. static void
  307. resume (scm_i_thread *t)
  308. {
  309. t->top = NULL;
  310. if (t->clear_freelists_p)
  311. {
  312. *SCM_FREELIST_LOC (scm_i_freelist) = SCM_EOL;
  313. *SCM_FREELIST_LOC (scm_i_freelist2) = SCM_EOL;
  314. t->clear_freelists_p = 0;
  315. }
  316. }
  317. typedef void* scm_t_guile_ticket;
  318. static void
  319. scm_enter_guile (scm_t_guile_ticket ticket)
  320. {
  321. scm_i_thread *t = (scm_i_thread *)ticket;
  322. if (t)
  323. {
  324. scm_i_pthread_mutex_lock (&t->heap_mutex);
  325. resume (t);
  326. }
  327. }
  328. static scm_i_thread *
  329. suspend (void)
  330. {
  331. scm_i_thread *t = SCM_I_CURRENT_THREAD;
  332. /* record top of stack for the GC */
  333. t->top = SCM_STACK_PTR (&t);
  334. /* save registers. */
  335. SCM_FLUSH_REGISTER_WINDOWS;
  336. setjmp (t->regs);
  337. return t;
  338. }
  339. static scm_t_guile_ticket
  340. scm_leave_guile ()
  341. {
  342. scm_i_thread *t = suspend ();
  343. scm_i_pthread_mutex_unlock (&t->heap_mutex);
  344. return (scm_t_guile_ticket) t;
  345. }
  346. static scm_i_pthread_mutex_t thread_admin_mutex = SCM_I_PTHREAD_MUTEX_INITIALIZER;
  347. static scm_i_thread *all_threads = NULL;
  348. static int thread_count;
  349. static SCM scm_i_default_dynamic_state;
  350. /* Perform first stage of thread initialisation, in non-guile mode.
  351. */
  352. static void
  353. guilify_self_1 (SCM_STACKITEM *base)
  354. {
  355. scm_i_thread *t = malloc (sizeof (scm_i_thread));
  356. t->pthread = scm_i_pthread_self ();
  357. t->handle = SCM_BOOL_F;
  358. t->result = SCM_BOOL_F;
  359. t->join_queue = SCM_EOL;
  360. t->dynamic_state = SCM_BOOL_F;
  361. t->dynwinds = SCM_EOL;
  362. t->active_asyncs = SCM_EOL;
  363. t->block_asyncs = 1;
  364. t->pending_asyncs = 1;
  365. t->critical_section_level = 0;
  366. t->last_debug_frame = NULL;
  367. t->base = base;
  368. #ifdef __ia64__
  369. /* Calculate and store off the base of this thread's register
  370. backing store (RBS). Unfortunately our implementation(s) of
  371. scm_ia64_register_backing_store_base are only reliable for the
  372. main thread. For other threads, therefore, find out the current
  373. top of the RBS, and use that as a maximum. */
  374. t->register_backing_store_base = scm_ia64_register_backing_store_base ();
  375. {
  376. ucontext_t ctx;
  377. void *bsp;
  378. getcontext (&ctx);
  379. bsp = scm_ia64_ar_bsp (&ctx);
  380. if (t->register_backing_store_base > bsp)
  381. t->register_backing_store_base = bsp;
  382. }
  383. #endif
  384. t->continuation_root = SCM_EOL;
  385. t->continuation_base = base;
  386. scm_i_pthread_cond_init (&t->sleep_cond, NULL);
  387. t->sleep_mutex = NULL;
  388. t->sleep_object = SCM_BOOL_F;
  389. t->sleep_fd = -1;
  390. if (pipe (t->sleep_pipe) != 0)
  391. /* FIXME: Error conditions during the initialization phase are handled
  392. gracelessly since public functions such as `scm_init_guile ()'
  393. currently have type `void'. */
  394. abort ();
  395. scm_i_pthread_mutex_init (&t->heap_mutex, NULL);
  396. t->clear_freelists_p = 0;
  397. t->gc_running_p = 0;
  398. t->exited = 0;
  399. t->freelist = SCM_EOL;
  400. t->freelist2 = SCM_EOL;
  401. SCM_SET_FREELIST_LOC (scm_i_freelist, &t->freelist);
  402. SCM_SET_FREELIST_LOC (scm_i_freelist2, &t->freelist2);
  403. scm_i_pthread_setspecific (scm_i_thread_key, t);
  404. /* As soon as this thread adds itself to the global thread list, the
  405. GC may think that it has a stack that needs marking. Therefore
  406. initialize t->top to be the same as t->base, just in case GC runs
  407. before the thread can lock its heap_mutex for the first time. */
  408. t->top = t->base;
  409. scm_i_pthread_mutex_lock (&thread_admin_mutex);
  410. t->next_thread = all_threads;
  411. all_threads = t;
  412. thread_count++;
  413. scm_i_pthread_mutex_unlock (&thread_admin_mutex);
  414. /* Enter Guile mode. */
  415. scm_enter_guile (t);
  416. }
  417. /* Perform second stage of thread initialisation, in guile mode.
  418. */
  419. static void
  420. guilify_self_2 (SCM parent)
  421. {
  422. scm_i_thread *t = SCM_I_CURRENT_THREAD;
  423. SCM_NEWSMOB (t->handle, scm_tc16_thread, t);
  424. scm_gc_register_collectable_memory (t, sizeof (scm_i_thread), "thread");
  425. t->continuation_root = scm_cons (t->handle, SCM_EOL);
  426. t->continuation_base = t->base;
  427. if (scm_is_true (parent))
  428. t->dynamic_state = scm_make_dynamic_state (parent);
  429. else
  430. t->dynamic_state = scm_i_make_initial_dynamic_state ();
  431. t->join_queue = make_queue ();
  432. t->block_asyncs = 0;
  433. }
  434. /* Perform thread tear-down, in guile mode.
  435. */
  436. static void *
  437. do_thread_exit (void *v)
  438. {
  439. scm_i_thread *t = (scm_i_thread *)v;
  440. scm_i_scm_pthread_mutex_lock (&thread_admin_mutex);
  441. t->exited = 1;
  442. close (t->sleep_pipe[0]);
  443. close (t->sleep_pipe[1]);
  444. while (scm_is_true (unblock_from_queue (t->join_queue)))
  445. ;
  446. scm_i_pthread_mutex_unlock (&thread_admin_mutex);
  447. return NULL;
  448. }
  449. static void
  450. on_thread_exit (void *v)
  451. {
  452. /* This handler is executed in non-guile mode. */
  453. scm_i_thread *t = (scm_i_thread *)v, **tp;
  454. scm_i_pthread_setspecific (scm_i_thread_key, v);
  455. /* Unblocking the joining threads needs to happen in guile mode
  456. since the queue is a SCM data structure. */
  457. scm_with_guile (do_thread_exit, v);
  458. /* Removing ourself from the list of all threads needs to happen in
  459. non-guile mode since all SCM values on our stack become
  460. unprotected once we are no longer in the list. */
  461. scm_i_pthread_mutex_lock (&thread_admin_mutex);
  462. for (tp = &all_threads; *tp; tp = &(*tp)->next_thread)
  463. if (*tp == t)
  464. {
  465. *tp = t->next_thread;
  466. break;
  467. }
  468. thread_count--;
  469. scm_i_pthread_mutex_unlock (&thread_admin_mutex);
  470. scm_i_pthread_setspecific (scm_i_thread_key, NULL);
  471. }
  472. static scm_i_pthread_once_t init_thread_key_once = SCM_I_PTHREAD_ONCE_INIT;
  473. static void
  474. init_thread_key (void)
  475. {
  476. scm_i_pthread_key_create (&scm_i_thread_key, on_thread_exit);
  477. }
  478. /* Perform any initializations necessary to bring the current thread
  479. into guile mode, initializing Guile itself, if necessary.
  480. BASE is the stack base to use with GC.
  481. PARENT is the dynamic state to use as the parent, ot SCM_BOOL_F in
  482. which case the default dynamic state is used.
  483. Return zero when the thread was in guile mode already; otherwise
  484. return 1.
  485. */
  486. static int
  487. scm_i_init_thread_for_guile (SCM_STACKITEM *base, SCM parent)
  488. {
  489. scm_i_thread *t;
  490. scm_i_pthread_once (&init_thread_key_once, init_thread_key);
  491. if ((t = SCM_I_CURRENT_THREAD) == NULL)
  492. {
  493. /* This thread has not been guilified yet.
  494. */
  495. scm_i_pthread_mutex_lock (&scm_i_init_mutex);
  496. if (scm_initialized_p == 0)
  497. {
  498. /* First thread ever to enter Guile. Run the full
  499. initialization.
  500. */
  501. scm_i_init_guile (base);
  502. scm_i_pthread_mutex_unlock (&scm_i_init_mutex);
  503. }
  504. else
  505. {
  506. /* Guile is already initialized, but this thread enters it for
  507. the first time. Only initialize this thread.
  508. */
  509. scm_i_pthread_mutex_unlock (&scm_i_init_mutex);
  510. guilify_self_1 (base);
  511. guilify_self_2 (parent);
  512. }
  513. return 1;
  514. }
  515. else if (t->top)
  516. {
  517. /* This thread is already guilified but not in guile mode, just
  518. resume it.
  519. A user call to scm_with_guile() will lead us to here. This could
  520. happen from anywhere on the stack, and in particular lower on the
  521. stack than when it was when this thread was first guilified. Thus,
  522. `base' must be updated. */
  523. #if SCM_STACK_GROWS_UP
  524. if (base < t->base)
  525. t->base = base;
  526. #else
  527. if (base > t->base)
  528. t->base = base;
  529. #endif
  530. scm_enter_guile ((scm_t_guile_ticket) t);
  531. return 1;
  532. }
  533. else
  534. {
  535. /* Thread is already in guile mode. Nothing to do.
  536. */
  537. return 0;
  538. }
  539. }
  540. #if SCM_USE_PTHREAD_THREADS
  541. #if HAVE_PTHREAD_ATTR_GETSTACK && HAVE_PTHREAD_GETATTR_NP
  542. /* This method for GNU/Linux and perhaps some other systems.
  543. It's not for MacOS X or Solaris 10, since pthread_getattr_np is not
  544. available on them. */
  545. #define HAVE_GET_THREAD_STACK_BASE
  546. static SCM_STACKITEM *
  547. get_thread_stack_base ()
  548. {
  549. pthread_attr_t attr;
  550. void *start, *end;
  551. size_t size;
  552. pthread_getattr_np (pthread_self (), &attr);
  553. pthread_attr_getstack (&attr, &start, &size);
  554. end = (char *)start + size;
  555. /* XXX - pthread_getattr_np from LinuxThreads does not seem to work
  556. for the main thread, but we can use scm_get_stack_base in that
  557. case.
  558. */
  559. #ifndef PTHREAD_ATTR_GETSTACK_WORKS
  560. if ((void *)&attr < start || (void *)&attr >= end)
  561. return scm_get_stack_base ();
  562. else
  563. #endif
  564. {
  565. #if SCM_STACK_GROWS_UP
  566. return start;
  567. #else
  568. return end;
  569. #endif
  570. }
  571. }
  572. #elif HAVE_PTHREAD_GET_STACKADDR_NP
  573. /* This method for MacOS X.
  574. It'd be nice if there was some documentation on pthread_get_stackaddr_np,
  575. but as of 2006 there's nothing obvious at apple.com. */
  576. #define HAVE_GET_THREAD_STACK_BASE
  577. static SCM_STACKITEM *
  578. get_thread_stack_base ()
  579. {
  580. return pthread_get_stackaddr_np (pthread_self ());
  581. }
  582. #elif defined (__MINGW32__)
  583. /* This method for mingw. In mingw the basic scm_get_stack_base can be used
  584. in any thread. We don't like hard-coding the name of a system, but there
  585. doesn't seem to be a cleaner way of knowing scm_get_stack_base can
  586. work. */
  587. #define HAVE_GET_THREAD_STACK_BASE
  588. static SCM_STACKITEM *
  589. get_thread_stack_base ()
  590. {
  591. return scm_get_stack_base ();
  592. }
  593. #endif /* pthread methods of get_thread_stack_base */
  594. #else /* !SCM_USE_PTHREAD_THREADS */
  595. #define HAVE_GET_THREAD_STACK_BASE
  596. static SCM_STACKITEM *
  597. get_thread_stack_base ()
  598. {
  599. return scm_get_stack_base ();
  600. }
  601. #endif /* !SCM_USE_PTHREAD_THREADS */
  602. #ifdef HAVE_GET_THREAD_STACK_BASE
  603. void
  604. scm_init_guile ()
  605. {
  606. scm_i_init_thread_for_guile (get_thread_stack_base (),
  607. scm_i_default_dynamic_state);
  608. }
  609. #endif
  610. void *
  611. scm_with_guile (void *(*func)(void *), void *data)
  612. {
  613. return scm_i_with_guile_and_parent (func, data,
  614. scm_i_default_dynamic_state);
  615. }
  616. void *
  617. scm_i_with_guile_and_parent (void *(*func)(void *), void *data,
  618. SCM parent)
  619. {
  620. void *res;
  621. int really_entered;
  622. SCM_STACKITEM base_item;
  623. really_entered = scm_i_init_thread_for_guile (&base_item, parent);
  624. res = scm_c_with_continuation_barrier (func, data);
  625. if (really_entered)
  626. scm_leave_guile ();
  627. return res;
  628. }
  629. void *
  630. scm_without_guile (void *(*func)(void *), void *data)
  631. {
  632. void *res;
  633. scm_t_guile_ticket t;
  634. t = scm_leave_guile ();
  635. res = func (data);
  636. scm_enter_guile (t);
  637. return res;
  638. }
  639. /*** Thread creation */
  640. typedef struct {
  641. SCM parent;
  642. SCM thunk;
  643. SCM handler;
  644. SCM thread;
  645. scm_i_pthread_mutex_t mutex;
  646. scm_i_pthread_cond_t cond;
  647. } launch_data;
  648. static void *
  649. really_launch (void *d)
  650. {
  651. launch_data *data = (launch_data *)d;
  652. SCM thunk = data->thunk, handler = data->handler;
  653. scm_i_thread *t;
  654. t = SCM_I_CURRENT_THREAD;
  655. scm_i_scm_pthread_mutex_lock (&data->mutex);
  656. data->thread = scm_current_thread ();
  657. scm_i_pthread_cond_signal (&data->cond);
  658. scm_i_pthread_mutex_unlock (&data->mutex);
  659. if (SCM_UNBNDP (handler))
  660. t->result = scm_call_0 (thunk);
  661. else
  662. t->result = scm_catch (SCM_BOOL_T, thunk, handler);
  663. return 0;
  664. }
  665. static void *
  666. launch_thread (void *d)
  667. {
  668. launch_data *data = (launch_data *)d;
  669. scm_i_pthread_detach (scm_i_pthread_self ());
  670. scm_i_with_guile_and_parent (really_launch, d, data->parent);
  671. return NULL;
  672. }
  673. SCM_DEFINE (scm_call_with_new_thread, "call-with-new-thread", 1, 1, 0,
  674. (SCM thunk, SCM handler),
  675. "Call @code{thunk} in a new thread and with a new dynamic state,\n"
  676. "returning a new thread object representing the thread. The procedure\n"
  677. "@var{thunk} is called via @code{with-continuation-barrier}.\n"
  678. "\n"
  679. "When @var{handler} is specified, then @var{thunk} is called from\n"
  680. "within a @code{catch} with tag @code{#t} that has @var{handler} as its\n"
  681. "handler. This catch is established inside the continuation barrier.\n"
  682. "\n"
  683. "Once @var{thunk} or @var{handler} returns, the return value is made\n"
  684. "the @emph{exit value} of the thread and the thread is terminated.")
  685. #define FUNC_NAME s_scm_call_with_new_thread
  686. {
  687. launch_data data;
  688. scm_i_pthread_t id;
  689. int err;
  690. SCM_ASSERT (scm_is_true (scm_thunk_p (thunk)), thunk, SCM_ARG1, FUNC_NAME);
  691. SCM_ASSERT (SCM_UNBNDP (handler) || scm_is_true (scm_procedure_p (handler)),
  692. handler, SCM_ARG2, FUNC_NAME);
  693. data.parent = scm_current_dynamic_state ();
  694. data.thunk = thunk;
  695. data.handler = handler;
  696. data.thread = SCM_BOOL_F;
  697. scm_i_pthread_mutex_init (&data.mutex, NULL);
  698. scm_i_pthread_cond_init (&data.cond, NULL);
  699. scm_i_scm_pthread_mutex_lock (&data.mutex);
  700. err = scm_i_pthread_create (&id, NULL, launch_thread, &data);
  701. if (err)
  702. {
  703. scm_i_pthread_mutex_unlock (&data.mutex);
  704. errno = err;
  705. scm_syserror (NULL);
  706. }
  707. scm_i_scm_pthread_cond_wait (&data.cond, &data.mutex);
  708. scm_i_pthread_mutex_unlock (&data.mutex);
  709. return data.thread;
  710. }
  711. #undef FUNC_NAME
  712. typedef struct {
  713. SCM parent;
  714. scm_t_catch_body body;
  715. void *body_data;
  716. scm_t_catch_handler handler;
  717. void *handler_data;
  718. SCM thread;
  719. scm_i_pthread_mutex_t mutex;
  720. scm_i_pthread_cond_t cond;
  721. } spawn_data;
  722. static void *
  723. really_spawn (void *d)
  724. {
  725. spawn_data *data = (spawn_data *)d;
  726. scm_t_catch_body body = data->body;
  727. void *body_data = data->body_data;
  728. scm_t_catch_handler handler = data->handler;
  729. void *handler_data = data->handler_data;
  730. scm_i_thread *t = SCM_I_CURRENT_THREAD;
  731. scm_i_scm_pthread_mutex_lock (&data->mutex);
  732. data->thread = scm_current_thread ();
  733. scm_i_pthread_cond_signal (&data->cond);
  734. scm_i_pthread_mutex_unlock (&data->mutex);
  735. if (handler == NULL)
  736. t->result = body (body_data);
  737. else
  738. t->result = scm_internal_catch (SCM_BOOL_T,
  739. body, body_data,
  740. handler, handler_data);
  741. return 0;
  742. }
  743. static void *
  744. spawn_thread (void *d)
  745. {
  746. spawn_data *data = (spawn_data *)d;
  747. scm_i_pthread_detach (scm_i_pthread_self ());
  748. scm_i_with_guile_and_parent (really_spawn, d, data->parent);
  749. return NULL;
  750. }
  751. SCM
  752. scm_spawn_thread (scm_t_catch_body body, void *body_data,
  753. scm_t_catch_handler handler, void *handler_data)
  754. {
  755. spawn_data data;
  756. scm_i_pthread_t id;
  757. int err;
  758. data.parent = scm_current_dynamic_state ();
  759. data.body = body;
  760. data.body_data = body_data;
  761. data.handler = handler;
  762. data.handler_data = handler_data;
  763. data.thread = SCM_BOOL_F;
  764. scm_i_pthread_mutex_init (&data.mutex, NULL);
  765. scm_i_pthread_cond_init (&data.cond, NULL);
  766. scm_i_scm_pthread_mutex_lock (&data.mutex);
  767. err = scm_i_pthread_create (&id, NULL, spawn_thread, &data);
  768. if (err)
  769. {
  770. scm_i_pthread_mutex_unlock (&data.mutex);
  771. errno = err;
  772. scm_syserror (NULL);
  773. }
  774. scm_i_scm_pthread_cond_wait (&data.cond, &data.mutex);
  775. scm_i_pthread_mutex_unlock (&data.mutex);
  776. return data.thread;
  777. }
  778. SCM_DEFINE (scm_yield, "yield", 0, 0, 0,
  779. (),
  780. "Move the calling thread to the end of the scheduling queue.")
  781. #define FUNC_NAME s_scm_yield
  782. {
  783. return scm_from_bool (scm_i_sched_yield ());
  784. }
  785. #undef FUNC_NAME
  786. SCM_DEFINE (scm_join_thread, "join-thread", 1, 0, 0,
  787. (SCM thread),
  788. "Suspend execution of the calling thread until the target @var{thread} "
  789. "terminates, unless the target @var{thread} has already terminated. ")
  790. #define FUNC_NAME s_scm_join_thread
  791. {
  792. scm_i_thread *t;
  793. SCM res;
  794. SCM_VALIDATE_THREAD (1, thread);
  795. if (scm_is_eq (scm_current_thread (), thread))
  796. SCM_MISC_ERROR ("can not join the current thread", SCM_EOL);
  797. scm_i_scm_pthread_mutex_lock (&thread_admin_mutex);
  798. t = SCM_I_THREAD_DATA (thread);
  799. while (!t->exited)
  800. {
  801. block_self (t->join_queue, thread, &thread_admin_mutex, NULL);
  802. if (t->exited)
  803. break;
  804. scm_i_pthread_mutex_unlock (&thread_admin_mutex);
  805. SCM_TICK;
  806. scm_i_scm_pthread_mutex_lock (&thread_admin_mutex);
  807. }
  808. res = t->result;
  809. scm_i_pthread_mutex_unlock (&thread_admin_mutex);
  810. return res;
  811. }
  812. #undef FUNC_NAME
  813. /*** Fat mutexes */
  814. /* We implement our own mutex type since we want them to be 'fair', we
  815. want to do fancy things while waiting for them (like running
  816. asyncs) and we might want to add things that are nice for
  817. debugging.
  818. */
  819. typedef struct {
  820. scm_i_pthread_mutex_t lock;
  821. SCM owner;
  822. int level; /* how much the owner owns us.
  823. < 0 for non-recursive mutexes */
  824. SCM waiting; /* the threads waiting for this mutex. */
  825. } fat_mutex;
  826. #define SCM_MUTEXP(x) SCM_SMOB_PREDICATE (scm_tc16_mutex, x)
  827. #define SCM_MUTEX_DATA(x) ((fat_mutex *) SCM_SMOB_DATA (x))
  828. static SCM
  829. fat_mutex_mark (SCM mx)
  830. {
  831. fat_mutex *m = SCM_MUTEX_DATA (mx);
  832. scm_gc_mark (m->owner);
  833. return m->waiting;
  834. }
  835. static size_t
  836. fat_mutex_free (SCM mx)
  837. {
  838. fat_mutex *m = SCM_MUTEX_DATA (mx);
  839. scm_i_pthread_mutex_destroy (&m->lock);
  840. scm_gc_free (m, sizeof (fat_mutex), "mutex");
  841. return 0;
  842. }
  843. static int
  844. fat_mutex_print (SCM mx, SCM port, scm_print_state *pstate SCM_UNUSED)
  845. {
  846. fat_mutex *m = SCM_MUTEX_DATA (mx);
  847. scm_puts ("#<mutex ", port);
  848. scm_uintprint ((scm_t_bits)m, 16, port);
  849. scm_puts (">", port);
  850. return 1;
  851. }
  852. static SCM
  853. make_fat_mutex (int recursive)
  854. {
  855. fat_mutex *m;
  856. SCM mx;
  857. m = scm_gc_malloc (sizeof (fat_mutex), "mutex");
  858. scm_i_pthread_mutex_init (&m->lock, NULL);
  859. m->owner = SCM_BOOL_F;
  860. m->level = recursive? 0 : -1;
  861. m->waiting = SCM_EOL;
  862. SCM_NEWSMOB (mx, scm_tc16_mutex, (scm_t_bits) m);
  863. m->waiting = make_queue ();
  864. return mx;
  865. }
  866. SCM_DEFINE (scm_make_mutex, "make-mutex", 0, 0, 0,
  867. (void),
  868. "Create a new mutex. ")
  869. #define FUNC_NAME s_scm_make_mutex
  870. {
  871. return make_fat_mutex (0);
  872. }
  873. #undef FUNC_NAME
  874. SCM_DEFINE (scm_make_recursive_mutex, "make-recursive-mutex", 0, 0, 0,
  875. (void),
  876. "Create a new recursive mutex. ")
  877. #define FUNC_NAME s_scm_make_recursive_mutex
  878. {
  879. return make_fat_mutex (1);
  880. }
  881. #undef FUNC_NAME
  882. static char *
  883. fat_mutex_lock (SCM mutex)
  884. {
  885. fat_mutex *m = SCM_MUTEX_DATA (mutex);
  886. SCM thread = scm_current_thread ();
  887. char *msg = NULL;
  888. scm_i_scm_pthread_mutex_lock (&m->lock);
  889. if (scm_is_false (m->owner))
  890. m->owner = thread;
  891. else if (scm_is_eq (m->owner, thread))
  892. {
  893. if (m->level >= 0)
  894. m->level++;
  895. else
  896. msg = "mutex already locked by current thread";
  897. }
  898. else
  899. {
  900. while (1)
  901. {
  902. if (scm_is_eq (m->owner, thread))
  903. break;
  904. block_self (m->waiting, mutex, &m->lock, NULL);
  905. scm_i_pthread_mutex_unlock (&m->lock);
  906. SCM_TICK;
  907. scm_i_scm_pthread_mutex_lock (&m->lock);
  908. }
  909. }
  910. scm_i_pthread_mutex_unlock (&m->lock);
  911. return msg;
  912. }
  913. SCM_DEFINE (scm_lock_mutex, "lock-mutex", 1, 0, 0,
  914. (SCM mx),
  915. "Lock @var{mutex}. If the mutex is already locked, the calling thread "
  916. "blocks until the mutex becomes available. The function returns when "
  917. "the calling thread owns the lock on @var{mutex}. Locking a mutex that "
  918. "a thread already owns will succeed right away and will not block the "
  919. "thread. That is, Guile's mutexes are @emph{recursive}. ")
  920. #define FUNC_NAME s_scm_lock_mutex
  921. {
  922. char *msg;
  923. SCM_VALIDATE_MUTEX (1, mx);
  924. msg = fat_mutex_lock (mx);
  925. if (msg)
  926. scm_misc_error (NULL, msg, SCM_EOL);
  927. return SCM_BOOL_T;
  928. }
  929. #undef FUNC_NAME
  930. void
  931. scm_dynwind_lock_mutex (SCM mutex)
  932. {
  933. scm_dynwind_unwind_handler_with_scm ((void(*)(SCM))scm_unlock_mutex, mutex,
  934. SCM_F_WIND_EXPLICITLY);
  935. scm_dynwind_rewind_handler_with_scm ((void(*)(SCM))scm_lock_mutex, mutex,
  936. SCM_F_WIND_EXPLICITLY);
  937. }
  938. static char *
  939. fat_mutex_trylock (fat_mutex *m, int *resp)
  940. {
  941. char *msg = NULL;
  942. SCM thread = scm_current_thread ();
  943. *resp = 1;
  944. scm_i_pthread_mutex_lock (&m->lock);
  945. if (scm_is_false (m->owner))
  946. m->owner = thread;
  947. else if (scm_is_eq (m->owner, thread))
  948. {
  949. if (m->level >= 0)
  950. m->level++;
  951. else
  952. msg = "mutex already locked by current thread";
  953. }
  954. else
  955. *resp = 0;
  956. scm_i_pthread_mutex_unlock (&m->lock);
  957. return msg;
  958. }
  959. SCM_DEFINE (scm_try_mutex, "try-mutex", 1, 0, 0,
  960. (SCM mutex),
  961. "Try to lock @var{mutex}. If the mutex is already locked by someone "
  962. "else, return @code{#f}. Else lock the mutex and return @code{#t}. ")
  963. #define FUNC_NAME s_scm_try_mutex
  964. {
  965. char *msg;
  966. int res;
  967. SCM_VALIDATE_MUTEX (1, mutex);
  968. msg = fat_mutex_trylock (SCM_MUTEX_DATA (mutex), &res);
  969. if (msg)
  970. scm_misc_error (NULL, msg, SCM_EOL);
  971. return scm_from_bool (res);
  972. }
  973. #undef FUNC_NAME
  974. static char *
  975. fat_mutex_unlock (fat_mutex *m)
  976. {
  977. char *msg = NULL;
  978. scm_i_scm_pthread_mutex_lock (&m->lock);
  979. if (!scm_is_eq (m->owner, scm_current_thread ()))
  980. {
  981. if (scm_is_false (m->owner))
  982. msg = "mutex not locked";
  983. else
  984. msg = "mutex not locked by current thread";
  985. }
  986. else if (m->level > 0)
  987. m->level--;
  988. else
  989. m->owner = unblock_from_queue (m->waiting);
  990. scm_i_pthread_mutex_unlock (&m->lock);
  991. return msg;
  992. }
  993. SCM_DEFINE (scm_unlock_mutex, "unlock-mutex", 1, 0, 0,
  994. (SCM mx),
  995. "Unlocks @var{mutex} if the calling thread owns the lock on "
  996. "@var{mutex}. Calling unlock-mutex on a mutex not owned by the current "
  997. "thread results in undefined behaviour. Once a mutex has been unlocked, "
  998. "one thread blocked on @var{mutex} is awakened and grabs the mutex "
  999. "lock. Every call to @code{lock-mutex} by this thread must be matched "
  1000. "with a call to @code{unlock-mutex}. Only the last call to "
  1001. "@code{unlock-mutex} will actually unlock the mutex. ")
  1002. #define FUNC_NAME s_scm_unlock_mutex
  1003. {
  1004. char *msg;
  1005. SCM_VALIDATE_MUTEX (1, mx);
  1006. msg = fat_mutex_unlock (SCM_MUTEX_DATA (mx));
  1007. if (msg)
  1008. scm_misc_error (NULL, msg, SCM_EOL);
  1009. return SCM_BOOL_T;
  1010. }
  1011. #undef FUNC_NAME
  1012. #if 0
  1013. SCM_DEFINE (scm_mutex_owner, "mutex-owner", 1, 0, 0,
  1014. (SCM mx),
  1015. "Return the thread owning @var{mx}, or @code{#f}.")
  1016. #define FUNC_NAME s_scm_mutex_owner
  1017. {
  1018. SCM_VALIDATE_MUTEX (1, mx);
  1019. return (SCM_MUTEX_DATA(mx))->owner;
  1020. }
  1021. #undef FUNC_NAME
  1022. SCM_DEFINE (scm_mutex_level, "mutex-level", 1, 0, 0,
  1023. (SCM mx),
  1024. "Return the lock level of a recursive mutex, or -1\n"
  1025. "for a standard mutex.")
  1026. #define FUNC_NAME s_scm_mutex_level
  1027. {
  1028. SCM_VALIDATE_MUTEX (1, mx);
  1029. return scm_from_int (SCM_MUTEX_DATA(mx)->level);
  1030. }
  1031. #undef FUNC_NAME
  1032. #endif
  1033. /*** Fat condition variables */
  1034. typedef struct {
  1035. scm_i_pthread_mutex_t lock;
  1036. SCM waiting; /* the threads waiting for this condition. */
  1037. } fat_cond;
  1038. #define SCM_CONDVARP(x) SCM_SMOB_PREDICATE (scm_tc16_condvar, x)
  1039. #define SCM_CONDVAR_DATA(x) ((fat_cond *) SCM_SMOB_DATA (x))
  1040. static SCM
  1041. fat_cond_mark (SCM cv)
  1042. {
  1043. fat_cond *c = SCM_CONDVAR_DATA (cv);
  1044. return c->waiting;
  1045. }
  1046. static size_t
  1047. fat_cond_free (SCM mx)
  1048. {
  1049. fat_cond *c = SCM_CONDVAR_DATA (mx);
  1050. scm_i_pthread_mutex_destroy (&c->lock);
  1051. scm_gc_free (c, sizeof (fat_cond), "condition-variable");
  1052. return 0;
  1053. }
  1054. static int
  1055. fat_cond_print (SCM cv, SCM port, scm_print_state *pstate SCM_UNUSED)
  1056. {
  1057. fat_cond *c = SCM_CONDVAR_DATA (cv);
  1058. scm_puts ("#<condition-variable ", port);
  1059. scm_uintprint ((scm_t_bits)c, 16, port);
  1060. scm_puts (">", port);
  1061. return 1;
  1062. }
  1063. SCM_DEFINE (scm_make_condition_variable, "make-condition-variable", 0, 0, 0,
  1064. (void),
  1065. "Make a new condition variable.")
  1066. #define FUNC_NAME s_scm_make_condition_variable
  1067. {
  1068. fat_cond *c;
  1069. SCM cv;
  1070. c = scm_gc_malloc (sizeof (fat_cond), "condition variable");
  1071. scm_i_pthread_mutex_init (&c->lock, 0);
  1072. c->waiting = SCM_EOL;
  1073. SCM_NEWSMOB (cv, scm_tc16_condvar, (scm_t_bits) c);
  1074. c->waiting = make_queue ();
  1075. return cv;
  1076. }
  1077. #undef FUNC_NAME
  1078. static int
  1079. fat_cond_timedwait (SCM cond, SCM mutex,
  1080. const scm_t_timespec *waittime)
  1081. {
  1082. scm_i_thread *t = SCM_I_CURRENT_THREAD;
  1083. fat_cond *c = SCM_CONDVAR_DATA (cond);
  1084. fat_mutex *m = SCM_MUTEX_DATA (mutex);
  1085. const char *msg;
  1086. int err = 0;
  1087. while (1)
  1088. {
  1089. scm_i_scm_pthread_mutex_lock (&c->lock);
  1090. msg = fat_mutex_unlock (m);
  1091. t->block_asyncs++;
  1092. if (msg == NULL)
  1093. {
  1094. err = block_self (c->waiting, cond, &c->lock, waittime);
  1095. scm_i_pthread_mutex_unlock (&c->lock);
  1096. fat_mutex_lock (mutex);
  1097. }
  1098. else
  1099. scm_i_pthread_mutex_unlock (&c->lock);
  1100. t->block_asyncs--;
  1101. scm_async_click ();
  1102. if (msg)
  1103. scm_misc_error (NULL, msg, SCM_EOL);
  1104. scm_remember_upto_here_2 (cond, mutex);
  1105. if (err == 0)
  1106. return 1;
  1107. if (err == ETIMEDOUT)
  1108. return 0;
  1109. if (err != EINTR)
  1110. {
  1111. errno = err;
  1112. scm_syserror (NULL);
  1113. }
  1114. }
  1115. }
  1116. SCM_DEFINE (scm_timed_wait_condition_variable, "wait-condition-variable", 2, 1, 0,
  1117. (SCM cv, SCM mx, SCM t),
  1118. "Wait until @var{cond-var} has been signalled. While waiting, "
  1119. "@var{mutex} is atomically unlocked (as with @code{unlock-mutex}) and "
  1120. "is locked again when this function returns. When @var{time} is given, "
  1121. "it specifies a point in time where the waiting should be aborted. It "
  1122. "can be either a integer as returned by @code{current-time} or a pair "
  1123. "as returned by @code{gettimeofday}. When the waiting is aborted the "
  1124. "mutex is locked and @code{#f} is returned. When the condition "
  1125. "variable is in fact signalled, the mutex is also locked and @code{#t} "
  1126. "is returned. ")
  1127. #define FUNC_NAME s_scm_timed_wait_condition_variable
  1128. {
  1129. scm_t_timespec waittime, *waitptr = NULL;
  1130. SCM_VALIDATE_CONDVAR (1, cv);
  1131. SCM_VALIDATE_MUTEX (2, mx);
  1132. if (!SCM_UNBNDP (t))
  1133. {
  1134. if (scm_is_pair (t))
  1135. {
  1136. waittime.tv_sec = scm_to_ulong (SCM_CAR (t));
  1137. waittime.tv_nsec = scm_to_ulong (SCM_CAR (t)) * 1000;
  1138. }
  1139. else
  1140. {
  1141. waittime.tv_sec = scm_to_ulong (t);
  1142. waittime.tv_nsec = 0;
  1143. }
  1144. waitptr = &waittime;
  1145. }
  1146. return scm_from_bool (fat_cond_timedwait (cv, mx, waitptr));
  1147. }
  1148. #undef FUNC_NAME
  1149. static void
  1150. fat_cond_signal (fat_cond *c)
  1151. {
  1152. scm_i_scm_pthread_mutex_lock (&c->lock);
  1153. unblock_from_queue (c->waiting);
  1154. scm_i_pthread_mutex_unlock (&c->lock);
  1155. }
  1156. SCM_DEFINE (scm_signal_condition_variable, "signal-condition-variable", 1, 0, 0,
  1157. (SCM cv),
  1158. "Wake up one thread that is waiting for @var{cv}")
  1159. #define FUNC_NAME s_scm_signal_condition_variable
  1160. {
  1161. SCM_VALIDATE_CONDVAR (1, cv);
  1162. fat_cond_signal (SCM_CONDVAR_DATA (cv));
  1163. return SCM_BOOL_T;
  1164. }
  1165. #undef FUNC_NAME
  1166. static void
  1167. fat_cond_broadcast (fat_cond *c)
  1168. {
  1169. scm_i_scm_pthread_mutex_lock (&c->lock);
  1170. while (scm_is_true (unblock_from_queue (c->waiting)))
  1171. ;
  1172. scm_i_pthread_mutex_unlock (&c->lock);
  1173. }
  1174. SCM_DEFINE (scm_broadcast_condition_variable, "broadcast-condition-variable", 1, 0, 0,
  1175. (SCM cv),
  1176. "Wake up all threads that are waiting for @var{cv}. ")
  1177. #define FUNC_NAME s_scm_broadcast_condition_variable
  1178. {
  1179. SCM_VALIDATE_CONDVAR (1, cv);
  1180. fat_cond_broadcast (SCM_CONDVAR_DATA (cv));
  1181. return SCM_BOOL_T;
  1182. }
  1183. #undef FUNC_NAME
  1184. /*** Marking stacks */
  1185. /* XXX - what to do with this? Do we need to handle this for blocked
  1186. threads as well?
  1187. */
  1188. #ifdef __ia64__
  1189. # define SCM_MARK_BACKING_STORE() do { \
  1190. ucontext_t ctx; \
  1191. SCM_STACKITEM * top, * bot; \
  1192. getcontext (&ctx); \
  1193. scm_mark_locations ((SCM_STACKITEM *) &ctx.uc_mcontext, \
  1194. ((size_t) (sizeof (SCM_STACKITEM) - 1 + sizeof ctx.uc_mcontext) \
  1195. / sizeof (SCM_STACKITEM))); \
  1196. bot = (SCM_STACKITEM *) SCM_I_CURRENT_THREAD->register_backing_store_base; \
  1197. top = (SCM_STACKITEM *) scm_ia64_ar_bsp (&ctx); \
  1198. scm_mark_locations (bot, top - bot); } while (0)
  1199. #else
  1200. # define SCM_MARK_BACKING_STORE()
  1201. #endif
  1202. void
  1203. scm_threads_mark_stacks (void)
  1204. {
  1205. scm_i_thread *t;
  1206. for (t = all_threads; t; t = t->next_thread)
  1207. {
  1208. /* Check that thread has indeed been suspended.
  1209. */
  1210. assert (t->top);
  1211. scm_gc_mark (t->handle);
  1212. #if SCM_STACK_GROWS_UP
  1213. scm_mark_locations (t->base, t->top - t->base);
  1214. #else
  1215. scm_mark_locations (t->top, t->base - t->top);
  1216. #endif
  1217. scm_mark_locations ((void *) &t->regs,
  1218. ((size_t) sizeof(t->regs)
  1219. / sizeof (SCM_STACKITEM)));
  1220. }
  1221. SCM_MARK_BACKING_STORE ();
  1222. }
  1223. /*** Select */
  1224. int
  1225. scm_std_select (int nfds,
  1226. SELECT_TYPE *readfds,
  1227. SELECT_TYPE *writefds,
  1228. SELECT_TYPE *exceptfds,
  1229. struct timeval *timeout)
  1230. {
  1231. fd_set my_readfds;
  1232. int res, eno, wakeup_fd;
  1233. scm_i_thread *t = SCM_I_CURRENT_THREAD;
  1234. scm_t_guile_ticket ticket;
  1235. if (readfds == NULL)
  1236. {
  1237. FD_ZERO (&my_readfds);
  1238. readfds = &my_readfds;
  1239. }
  1240. while (scm_i_setup_sleep (t, SCM_BOOL_F, NULL, t->sleep_pipe[1]))
  1241. SCM_TICK;
  1242. wakeup_fd = t->sleep_pipe[0];
  1243. ticket = scm_leave_guile ();
  1244. FD_SET (wakeup_fd, readfds);
  1245. if (wakeup_fd >= nfds)
  1246. nfds = wakeup_fd+1;
  1247. res = select (nfds, readfds, writefds, exceptfds, timeout);
  1248. t->sleep_fd = -1;
  1249. eno = errno;
  1250. scm_enter_guile (ticket);
  1251. scm_i_reset_sleep (t);
  1252. if (res > 0 && FD_ISSET (wakeup_fd, readfds))
  1253. {
  1254. char dummy;
  1255. size_t count;
  1256. count = read (wakeup_fd, &dummy, 1);
  1257. FD_CLR (wakeup_fd, readfds);
  1258. res -= 1;
  1259. if (res == 0)
  1260. {
  1261. eno = EINTR;
  1262. res = -1;
  1263. }
  1264. }
  1265. errno = eno;
  1266. return res;
  1267. }
  1268. /* Convenience API for blocking while in guile mode. */
  1269. #if SCM_USE_PTHREAD_THREADS
  1270. int
  1271. scm_pthread_mutex_lock (scm_i_pthread_mutex_t *mutex)
  1272. {
  1273. scm_t_guile_ticket t = scm_leave_guile ();
  1274. int res = scm_i_pthread_mutex_lock (mutex);
  1275. scm_enter_guile (t);
  1276. return res;
  1277. }
  1278. static void
  1279. do_unlock (void *data)
  1280. {
  1281. scm_i_pthread_mutex_unlock ((scm_i_pthread_mutex_t *)data);
  1282. }
  1283. void
  1284. scm_dynwind_pthread_mutex_lock (scm_i_pthread_mutex_t *mutex)
  1285. {
  1286. scm_i_scm_pthread_mutex_lock (mutex);
  1287. scm_dynwind_unwind_handler (do_unlock, mutex, SCM_F_WIND_EXPLICITLY);
  1288. }
  1289. int
  1290. scm_pthread_cond_wait (scm_i_pthread_cond_t *cond, scm_i_pthread_mutex_t *mutex)
  1291. {
  1292. scm_t_guile_ticket t = scm_leave_guile ();
  1293. int res = scm_i_pthread_cond_wait (cond, mutex);
  1294. scm_enter_guile (t);
  1295. return res;
  1296. }
  1297. int
  1298. scm_pthread_cond_timedwait (scm_i_pthread_cond_t *cond,
  1299. scm_i_pthread_mutex_t *mutex,
  1300. const scm_t_timespec *wt)
  1301. {
  1302. scm_t_guile_ticket t = scm_leave_guile ();
  1303. int res = scm_i_pthread_cond_timedwait (cond, mutex, wt);
  1304. scm_enter_guile (t);
  1305. return res;
  1306. }
  1307. #endif
  1308. unsigned long
  1309. scm_std_usleep (unsigned long usecs)
  1310. {
  1311. struct timeval tv;
  1312. tv.tv_usec = usecs % 1000000;
  1313. tv.tv_sec = usecs / 1000000;
  1314. scm_std_select (0, NULL, NULL, NULL, &tv);
  1315. return tv.tv_sec * 1000000 + tv.tv_usec;
  1316. }
  1317. unsigned int
  1318. scm_std_sleep (unsigned int secs)
  1319. {
  1320. struct timeval tv;
  1321. tv.tv_usec = 0;
  1322. tv.tv_sec = secs;
  1323. scm_std_select (0, NULL, NULL, NULL, &tv);
  1324. return tv.tv_sec;
  1325. }
  1326. /*** Misc */
  1327. SCM_DEFINE (scm_current_thread, "current-thread", 0, 0, 0,
  1328. (void),
  1329. "Return the thread that called this function.")
  1330. #define FUNC_NAME s_scm_current_thread
  1331. {
  1332. return SCM_I_CURRENT_THREAD->handle;
  1333. }
  1334. #undef FUNC_NAME
  1335. static SCM
  1336. scm_c_make_list (size_t n, SCM fill)
  1337. {
  1338. SCM res = SCM_EOL;
  1339. while (n-- > 0)
  1340. res = scm_cons (fill, res);
  1341. return res;
  1342. }
  1343. SCM_DEFINE (scm_all_threads, "all-threads", 0, 0, 0,
  1344. (void),
  1345. "Return a list of all threads.")
  1346. #define FUNC_NAME s_scm_all_threads
  1347. {
  1348. /* We can not allocate while holding the thread_admin_mutex because
  1349. of the way GC is done.
  1350. */
  1351. int n = thread_count;
  1352. scm_i_thread *t;
  1353. SCM list = scm_c_make_list (n, SCM_UNSPECIFIED), *l;
  1354. scm_i_pthread_mutex_lock (&thread_admin_mutex);
  1355. l = &list;
  1356. for (t = all_threads; t && n > 0; t = t->next_thread)
  1357. {
  1358. SCM_SETCAR (*l, t->handle);
  1359. l = SCM_CDRLOC (*l);
  1360. n--;
  1361. }
  1362. *l = SCM_EOL;
  1363. scm_i_pthread_mutex_unlock (&thread_admin_mutex);
  1364. return list;
  1365. }
  1366. #undef FUNC_NAME
  1367. SCM_DEFINE (scm_thread_exited_p, "thread-exited?", 1, 0, 0,
  1368. (SCM thread),
  1369. "Return @code{#t} iff @var{thread} has exited.\n")
  1370. #define FUNC_NAME s_scm_thread_exited_p
  1371. {
  1372. return scm_from_bool (scm_c_thread_exited_p (thread));
  1373. }
  1374. #undef FUNC_NAME
  1375. int
  1376. scm_c_thread_exited_p (SCM thread)
  1377. #define FUNC_NAME s_scm_thread_exited_p
  1378. {
  1379. scm_i_thread *t;
  1380. SCM_VALIDATE_THREAD (1, thread);
  1381. t = SCM_I_THREAD_DATA (thread);
  1382. return t->exited;
  1383. }
  1384. #undef FUNC_NAME
  1385. static scm_i_pthread_cond_t wake_up_cond;
  1386. int scm_i_thread_go_to_sleep;
  1387. static int threads_initialized_p = 0;
  1388. void
  1389. scm_i_thread_put_to_sleep ()
  1390. {
  1391. if (threads_initialized_p)
  1392. {
  1393. scm_i_thread *t;
  1394. scm_leave_guile ();
  1395. scm_i_pthread_mutex_lock (&thread_admin_mutex);
  1396. /* Signal all threads to go to sleep
  1397. */
  1398. scm_i_thread_go_to_sleep = 1;
  1399. for (t = all_threads; t; t = t->next_thread)
  1400. scm_i_pthread_mutex_lock (&t->heap_mutex);
  1401. scm_i_thread_go_to_sleep = 0;
  1402. }
  1403. }
  1404. void
  1405. scm_i_thread_invalidate_freelists ()
  1406. {
  1407. /* thread_admin_mutex is already locked. */
  1408. scm_i_thread *t;
  1409. for (t = all_threads; t; t = t->next_thread)
  1410. if (t != SCM_I_CURRENT_THREAD)
  1411. t->clear_freelists_p = 1;
  1412. }
  1413. void
  1414. scm_i_thread_wake_up ()
  1415. {
  1416. if (threads_initialized_p)
  1417. {
  1418. scm_i_thread *t;
  1419. scm_i_pthread_cond_broadcast (&wake_up_cond);
  1420. for (t = all_threads; t; t = t->next_thread)
  1421. scm_i_pthread_mutex_unlock (&t->heap_mutex);
  1422. scm_i_pthread_mutex_unlock (&thread_admin_mutex);
  1423. scm_enter_guile ((scm_t_guile_ticket) SCM_I_CURRENT_THREAD);
  1424. }
  1425. }
  1426. void
  1427. scm_i_thread_sleep_for_gc ()
  1428. {
  1429. scm_i_thread *t = suspend ();
  1430. scm_i_pthread_cond_wait (&wake_up_cond, &t->heap_mutex);
  1431. resume (t);
  1432. }
  1433. /* This mutex is used by SCM_CRITICAL_SECTION_START/END.
  1434. */
  1435. scm_i_pthread_mutex_t scm_i_critical_section_mutex;
  1436. static SCM dynwind_critical_section_mutex;
  1437. void
  1438. scm_dynwind_critical_section (SCM mutex)
  1439. {
  1440. if (scm_is_false (mutex))
  1441. mutex = dynwind_critical_section_mutex;
  1442. scm_dynwind_lock_mutex (mutex);
  1443. scm_dynwind_block_asyncs ();
  1444. }
  1445. /*** Initialization */
  1446. scm_i_pthread_key_t scm_i_freelist, scm_i_freelist2;
  1447. #ifdef __MINGW32__
  1448. scm_i_pthread_key_t *scm_i_freelist_ptr = &scm_i_freelist;
  1449. scm_i_pthread_key_t *scm_i_freelist2_ptr = &scm_i_freelist2;
  1450. #endif
  1451. scm_i_pthread_mutex_t scm_i_misc_mutex;
  1452. #if SCM_USE_PTHREAD_THREADS
  1453. pthread_mutexattr_t scm_i_pthread_mutexattr_recursive[1];
  1454. #endif
  1455. void
  1456. scm_threads_prehistory (SCM_STACKITEM *base)
  1457. {
  1458. #if SCM_USE_PTHREAD_THREADS
  1459. pthread_mutexattr_init (scm_i_pthread_mutexattr_recursive);
  1460. pthread_mutexattr_settype (scm_i_pthread_mutexattr_recursive,
  1461. PTHREAD_MUTEX_RECURSIVE);
  1462. #endif
  1463. scm_i_pthread_mutex_init (&scm_i_critical_section_mutex,
  1464. scm_i_pthread_mutexattr_recursive);
  1465. scm_i_pthread_mutex_init (&scm_i_misc_mutex, NULL);
  1466. scm_i_pthread_cond_init (&wake_up_cond, NULL);
  1467. scm_i_pthread_key_create (&scm_i_freelist, NULL);
  1468. scm_i_pthread_key_create (&scm_i_freelist2, NULL);
  1469. guilify_self_1 (base);
  1470. }
  1471. scm_t_bits scm_tc16_thread;
  1472. scm_t_bits scm_tc16_mutex;
  1473. scm_t_bits scm_tc16_condvar;
  1474. void
  1475. scm_init_threads ()
  1476. {
  1477. scm_tc16_thread = scm_make_smob_type ("thread", sizeof (scm_i_thread));
  1478. scm_set_smob_mark (scm_tc16_thread, thread_mark);
  1479. scm_set_smob_print (scm_tc16_thread, thread_print);
  1480. scm_set_smob_free (scm_tc16_thread, thread_free);
  1481. scm_tc16_mutex = scm_make_smob_type ("mutex", sizeof (fat_mutex));
  1482. scm_set_smob_mark (scm_tc16_mutex, fat_mutex_mark);
  1483. scm_set_smob_print (scm_tc16_mutex, fat_mutex_print);
  1484. scm_set_smob_free (scm_tc16_mutex, fat_mutex_free);
  1485. scm_tc16_condvar = scm_make_smob_type ("condition-variable",
  1486. sizeof (fat_cond));
  1487. scm_set_smob_mark (scm_tc16_condvar, fat_cond_mark);
  1488. scm_set_smob_print (scm_tc16_condvar, fat_cond_print);
  1489. scm_set_smob_free (scm_tc16_condvar, fat_cond_free);
  1490. scm_i_default_dynamic_state = SCM_BOOL_F;
  1491. guilify_self_2 (SCM_BOOL_F);
  1492. threads_initialized_p = 1;
  1493. dynwind_critical_section_mutex =
  1494. scm_permanent_object (scm_make_recursive_mutex ());
  1495. }
  1496. void
  1497. scm_init_threads_default_dynamic_state ()
  1498. {
  1499. SCM state = scm_make_dynamic_state (scm_current_dynamic_state ());
  1500. scm_i_default_dynamic_state = scm_permanent_object (state);
  1501. }
  1502. void
  1503. scm_init_thread_procs ()
  1504. {
  1505. #include "libguile/threads.x"
  1506. }
  1507. /*
  1508. Local Variables:
  1509. c-file-style: "gnu"
  1510. End:
  1511. */