threads.c 46 KB

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