threads.c 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848
  1. /* Copyright 1995-1998,2000-2014,2018
  2. Free Software Foundation, Inc.
  3. This file is part of Guile.
  4. Guile is free software: you can redistribute it and/or modify it
  5. under the terms of the GNU Lesser General Public License as published
  6. by the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. Guile is distributed in the hope that it will be useful, but WITHOUT
  9. ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10. FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
  11. License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with Guile. If not, see
  14. <https://www.gnu.org/licenses/>. */
  15. #ifdef HAVE_CONFIG_H
  16. # include <config.h>
  17. #endif
  18. #include <assert.h>
  19. #include <errno.h>
  20. #include <fcntl.h>
  21. #include <full-read.h>
  22. #include <nproc.h>
  23. #include <stdio.h>
  24. #include <stdlib.h>
  25. #include <string.h> /* for memset used by FD_ZERO on Solaris 10 */
  26. #include <sys/time.h>
  27. #include <unistd.h>
  28. #if HAVE_PTHREAD_NP_H
  29. # include <pthread_np.h>
  30. #endif
  31. #include "async.h"
  32. #include "bdw-gc.h"
  33. #include "boolean.h"
  34. #include "continuations.h"
  35. #include "deprecation.h"
  36. #include "dynwind.h"
  37. #include "eval.h"
  38. #include "extensions.h"
  39. #include "fluids.h"
  40. #include "gc-inline.h"
  41. #include "gc.h"
  42. #include "gsubr.h"
  43. #include "hashtab.h"
  44. #include "init.h"
  45. #include "iselect.h"
  46. #include "jit.h"
  47. #include "list.h"
  48. #include "modules.h"
  49. #include "numbers.h"
  50. #include "pairs.h"
  51. #include "ports.h"
  52. #include "scmsigs.h"
  53. #include "strings.h"
  54. #include "symbols.h"
  55. #include "variable.h"
  56. #include "version.h"
  57. #include "vm.h"
  58. #include "threads.h"
  59. #include <gc/gc_mark.h>
  60. /* The GC "kind" for threads that allow them to mark their VM
  61. stacks. */
  62. static int thread_gc_kind;
  63. static struct GC_ms_entry *
  64. thread_mark (GC_word *addr, struct GC_ms_entry *mark_stack_ptr,
  65. struct GC_ms_entry *mark_stack_limit, GC_word env)
  66. {
  67. int word;
  68. struct scm_thread *t = (struct scm_thread *) addr;
  69. if (SCM_UNPACK (t->handle) == 0)
  70. /* T must be on the free-list; ignore. (See warning in
  71. gc_mark.h.) */
  72. return mark_stack_ptr;
  73. /* Mark T. We could be more precise, but it doesn't matter. */
  74. for (word = 0; word * sizeof (*addr) < sizeof (*t); word++)
  75. mark_stack_ptr = GC_MARK_AND_PUSH ((void *) addr[word],
  76. mark_stack_ptr, mark_stack_limit,
  77. NULL);
  78. /* The pointerless freelists are threaded through their first word,
  79. but GC doesn't know to trace them (as they are pointerless), so we
  80. need to do that here. See the comments at the top of libgc's
  81. gc_inline.h. */
  82. if (t->pointerless_freelists)
  83. {
  84. size_t n;
  85. for (n = 0; n < SCM_INLINE_GC_FREELIST_COUNT; n++)
  86. {
  87. void *chain = t->pointerless_freelists[n];
  88. if (chain)
  89. {
  90. /* The first link is already marked by the freelist vector,
  91. so we just have to mark the tail. */
  92. while ((chain = *(void **)chain))
  93. mark_stack_ptr = GC_mark_and_push (chain, mark_stack_ptr,
  94. mark_stack_limit, NULL);
  95. }
  96. }
  97. }
  98. mark_stack_ptr = scm_i_vm_mark_stack (&t->vm, mark_stack_ptr,
  99. mark_stack_limit);
  100. return mark_stack_ptr;
  101. }
  102. static void
  103. to_timespec (SCM t, scm_t_timespec *waittime)
  104. {
  105. if (scm_is_pair (t))
  106. {
  107. waittime->tv_sec = scm_to_ulong (SCM_CAR (t));
  108. waittime->tv_nsec = scm_to_ulong (SCM_CDR (t)) * 1000;
  109. }
  110. else
  111. {
  112. double time = scm_to_double (t);
  113. double sec = scm_c_truncate (time);
  114. waittime->tv_sec = (long) sec;
  115. waittime->tv_nsec = (long) ((time - sec) * 1000000000);
  116. }
  117. }
  118. /*** Queues */
  119. /* Note: We annotate with "GC-robust" assignments whose purpose is to avoid
  120. the risk of false references leading to unbounded retained space as
  121. described in "Bounding Space Usage of Conservative Garbage Collectors",
  122. H.J. Boehm, 2001. */
  123. /* Make an empty queue data structure.
  124. */
  125. static SCM
  126. make_queue ()
  127. {
  128. return scm_cons (SCM_EOL, SCM_EOL);
  129. }
  130. static scm_i_pthread_mutex_t queue_lock = SCM_I_PTHREAD_MUTEX_INITIALIZER;
  131. /* Put T at the back of Q and return a handle that can be used with
  132. remqueue to remove T from Q again.
  133. */
  134. static SCM
  135. enqueue (SCM q, SCM t)
  136. {
  137. SCM c = scm_cons (t, SCM_EOL);
  138. scm_i_pthread_mutex_lock (&queue_lock);
  139. if (scm_is_null (SCM_CDR (q)))
  140. SCM_SETCDR (q, c);
  141. else
  142. SCM_SETCDR (SCM_CAR (q), c);
  143. SCM_SETCAR (q, c);
  144. scm_i_pthread_mutex_unlock (&queue_lock);
  145. return c;
  146. }
  147. /* Remove the element that the handle C refers to from the queue Q. C
  148. must have been returned from a call to enqueue. The return value
  149. is zero when the element referred to by C has already been removed.
  150. Otherwise, 1 is returned.
  151. */
  152. static int
  153. remqueue (SCM q, SCM c)
  154. {
  155. SCM p, prev = q;
  156. scm_i_pthread_mutex_lock (&queue_lock);
  157. for (p = SCM_CDR (q); !scm_is_null (p); p = SCM_CDR (p))
  158. {
  159. if (scm_is_eq (p, c))
  160. {
  161. if (scm_is_eq (c, SCM_CAR (q)))
  162. SCM_SETCAR (q, scm_is_eq (prev, q) ? SCM_EOL : prev);
  163. SCM_SETCDR (prev, SCM_CDR (c));
  164. /* GC-robust */
  165. SCM_SETCDR (c, SCM_EOL);
  166. scm_i_pthread_mutex_unlock (&queue_lock);
  167. return 1;
  168. }
  169. prev = p;
  170. }
  171. scm_i_pthread_mutex_unlock (&queue_lock);
  172. return 0;
  173. }
  174. /* Remove the front-most element from the queue Q and return it.
  175. Return SCM_BOOL_F when Q is empty.
  176. */
  177. static SCM
  178. dequeue (SCM q)
  179. {
  180. SCM c;
  181. scm_i_pthread_mutex_lock (&queue_lock);
  182. c = SCM_CDR (q);
  183. if (scm_is_null (c))
  184. {
  185. scm_i_pthread_mutex_unlock (&queue_lock);
  186. return SCM_BOOL_F;
  187. }
  188. else
  189. {
  190. SCM_SETCDR (q, SCM_CDR (c));
  191. if (scm_is_null (SCM_CDR (q)))
  192. SCM_SETCAR (q, SCM_EOL);
  193. scm_i_pthread_mutex_unlock (&queue_lock);
  194. /* GC-robust */
  195. SCM_SETCDR (c, SCM_EOL);
  196. return SCM_CAR (c);
  197. }
  198. }
  199. /*** Thread smob routines */
  200. static int
  201. thread_print (SCM exp, SCM port, scm_print_state *pstate SCM_UNUSED)
  202. {
  203. /* On a Gnu system pthread_t is an unsigned long, but on mingw it's a
  204. struct. A cast like "(unsigned long) t->pthread" is a syntax error in
  205. the struct case, hence we go via a union, and extract according to the
  206. size of pthread_t. */
  207. union {
  208. scm_i_pthread_t p;
  209. unsigned short us;
  210. unsigned int ui;
  211. unsigned long ul;
  212. uintmax_t um;
  213. } u;
  214. scm_thread *t = SCM_I_THREAD_DATA (exp);
  215. scm_i_pthread_t p = t->pthread;
  216. uintmax_t id;
  217. u.p = p;
  218. if (sizeof (p) == sizeof (unsigned short))
  219. id = u.us;
  220. else if (sizeof (p) == sizeof (unsigned int))
  221. id = u.ui;
  222. else if (sizeof (p) == sizeof (unsigned long))
  223. id = u.ul;
  224. else
  225. id = u.um;
  226. scm_puts ("#<thread ", port);
  227. scm_uintprint (id, 10, port);
  228. scm_puts (" (", port);
  229. scm_uintprint ((scm_t_bits)t, 16, port);
  230. scm_puts (")>", port);
  231. return 1;
  232. }
  233. /*** Blocking on queues. */
  234. /* See also scm_system_async_mark_for_thread for how such a block is
  235. interrputed.
  236. */
  237. /* Put the current thread on QUEUE and go to sleep, waiting for it to
  238. be woken up by a call to 'unblock_from_queue', or to be
  239. interrupted. Upon return of this function, the current thread is
  240. no longer on QUEUE, even when the sleep has been interrupted.
  241. The caller of block_self must hold MUTEX. It will be atomically
  242. unlocked while sleeping, just as with scm_i_pthread_cond_wait.
  243. When WAITTIME is not NULL, the sleep will be aborted at that time.
  244. The return value of block_self is an errno value. It will be zero
  245. when the sleep has been successfully completed by a call to
  246. unblock_from_queue, EINTR when it has been interrupted by the
  247. delivery of a system async, and ETIMEDOUT when the timeout has
  248. expired.
  249. The system asyncs themselves are not executed by block_self.
  250. */
  251. static int
  252. block_self (SCM queue, scm_i_pthread_mutex_t *mutex,
  253. const scm_t_timespec *waittime)
  254. {
  255. scm_thread *t = SCM_I_CURRENT_THREAD;
  256. SCM q_handle;
  257. int err;
  258. if (scm_i_prepare_to_wait_on_cond (t, mutex, &t->sleep_cond))
  259. return EINTR;
  260. t->block_asyncs++;
  261. q_handle = enqueue (queue, t->handle);
  262. if (waittime == NULL)
  263. err = scm_i_scm_pthread_cond_wait (&t->sleep_cond, mutex);
  264. else
  265. err = scm_i_scm_pthread_cond_timedwait (&t->sleep_cond, mutex, waittime);
  266. /* When we are still on QUEUE, we have been interrupted. We
  267. report this only when no other error (such as a timeout) has
  268. happened above.
  269. */
  270. if (remqueue (queue, q_handle) && err == 0)
  271. err = EINTR;
  272. t->block_asyncs--;
  273. scm_i_wait_finished (t);
  274. return err;
  275. }
  276. /* Wake up the first thread on QUEUE, if any. The awoken thread is
  277. returned, or #f if the queue was empty.
  278. */
  279. static SCM
  280. unblock_from_queue (SCM queue)
  281. {
  282. SCM thread = dequeue (queue);
  283. if (scm_is_true (thread))
  284. scm_i_pthread_cond_signal (&SCM_I_THREAD_DATA(thread)->sleep_cond);
  285. return thread;
  286. }
  287. /* Getting into and out of guile mode.
  288. */
  289. /* Key used to attach a cleanup handler to a given thread. Also, if
  290. thread-local storage is unavailable, this key is used to retrieve the
  291. current thread with `pthread_getspecific ()'. */
  292. scm_i_pthread_key_t scm_i_thread_key;
  293. #ifdef SCM_HAVE_THREAD_STORAGE_CLASS
  294. /* When thread-local storage (TLS) is available, a pointer to the
  295. current-thread object is kept in TLS. Note that storing the thread-object
  296. itself in TLS (rather than a pointer to some malloc'd memory) is not
  297. possible since thread objects may live longer than the actual thread they
  298. represent. */
  299. SCM_THREAD_LOCAL scm_thread *scm_i_current_thread = NULL;
  300. #endif /* SCM_HAVE_THREAD_STORAGE_CLASS */
  301. static scm_i_pthread_mutex_t thread_admin_mutex = SCM_I_PTHREAD_MUTEX_INITIALIZER;
  302. static scm_thread *all_threads = NULL;
  303. static int thread_count;
  304. static SCM default_dynamic_state;
  305. /* Perform first stage of thread initialisation, in non-guile mode.
  306. */
  307. static void
  308. guilify_self_1 (struct GC_stack_base *base, int needs_unregister)
  309. {
  310. scm_thread t;
  311. /* We must arrange for SCM_I_CURRENT_THREAD to point to a valid value
  312. before allocating anything in this thread, because allocation could
  313. cause GC to run, and GC could cause finalizers, which could invoke
  314. Scheme functions, which need the current thread to be set. */
  315. memset (&t, 0, sizeof (t));
  316. t.pthread = scm_i_pthread_self ();
  317. t.handle = SCM_BOOL_F;
  318. t.result = SCM_BOOL_F;
  319. t.pending_asyncs = SCM_EOL;
  320. t.block_asyncs = 1;
  321. t.base = base->mem_base;
  322. t.continuation_root = SCM_EOL;
  323. t.continuation_base = t.base;
  324. scm_i_pthread_cond_init (&t.sleep_cond, NULL);
  325. scm_i_vm_prepare_stack (&t.vm);
  326. if (pipe2 (t.sleep_pipe, O_CLOEXEC) != 0)
  327. /* FIXME: Error conditions during the initialization phase are handled
  328. gracelessly since public functions such as `scm_init_guile ()'
  329. currently have type `void'. */
  330. abort ();
  331. t.exited = 0;
  332. t.guile_mode = 0;
  333. t.needs_unregister = needs_unregister;
  334. /* The switcheroo. */
  335. {
  336. scm_thread *t_ptr = &t;
  337. GC_disable ();
  338. t_ptr = GC_generic_malloc (sizeof (*t_ptr), thread_gc_kind);
  339. memcpy (t_ptr, &t, sizeof t);
  340. scm_i_pthread_setspecific (scm_i_thread_key, t_ptr);
  341. #ifdef SCM_HAVE_THREAD_STORAGE_CLASS
  342. /* Cache the current thread in TLS for faster lookup. */
  343. scm_i_current_thread = t_ptr;
  344. #endif
  345. scm_i_pthread_mutex_lock (&thread_admin_mutex);
  346. t_ptr->next_thread = all_threads;
  347. all_threads = t_ptr;
  348. thread_count++;
  349. scm_i_pthread_mutex_unlock (&thread_admin_mutex);
  350. GC_enable ();
  351. }
  352. }
  353. /* Perform second stage of thread initialisation, in guile mode.
  354. */
  355. static void
  356. guilify_self_2 (SCM dynamic_state)
  357. {
  358. scm_thread *t = SCM_I_CURRENT_THREAD;
  359. t->guile_mode = 1;
  360. SCM_NEWSMOB (t->handle, scm_tc16_thread, t);
  361. t->continuation_root = scm_cons (t->handle, SCM_EOL);
  362. t->continuation_base = t->base;
  363. {
  364. size_t size = SCM_INLINE_GC_FREELIST_COUNT * sizeof (void *);
  365. t->freelists = scm_gc_malloc (size, "freelists");
  366. t->pointerless_freelists = scm_gc_malloc (size, "atomic freelists");
  367. }
  368. t->dynamic_state = scm_gc_typed_calloc (scm_t_dynamic_state);
  369. t->dynamic_state->thread_local_values = scm_c_make_hash_table (0);
  370. scm_set_current_dynamic_state (dynamic_state);
  371. t->dynstack.base = scm_gc_malloc (16 * sizeof (scm_t_bits), "dynstack");
  372. t->dynstack.limit = t->dynstack.base + 16;
  373. t->dynstack.top = t->dynstack.base + SCM_DYNSTACK_HEADER_LEN;
  374. t->block_asyncs = 0;
  375. /* See note in finalizers.c:queue_finalizer_async(). */
  376. GC_invoke_finalizers ();
  377. }
  378. static void
  379. on_thread_exit (void *v)
  380. {
  381. /* This handler is executed in non-guile mode. Note that although
  382. libgc isn't guaranteed to see thread-locals, for this thread-local
  383. that isn't an issue as we have the all_threads list. */
  384. scm_thread *t = (scm_thread *) v, **tp;
  385. t->exited = 1;
  386. close (t->sleep_pipe[0]);
  387. close (t->sleep_pipe[1]);
  388. t->sleep_pipe[0] = t->sleep_pipe[1] = -1;
  389. scm_i_pthread_mutex_lock (&thread_admin_mutex);
  390. for (tp = &all_threads; *tp; tp = &(*tp)->next_thread)
  391. if (*tp == t)
  392. {
  393. *tp = t->next_thread;
  394. /* GC-robust */
  395. t->next_thread = NULL;
  396. break;
  397. }
  398. thread_count--;
  399. /* Prevent any concurrent or future marker from visiting this
  400. thread. */
  401. t->handle = SCM_PACK (0);
  402. /* If there's only one other thread, it could be the signal delivery
  403. thread, so we need to notify it to shut down by closing its read pipe.
  404. If it's not the signal delivery thread, then closing the read pipe isn't
  405. going to hurt. */
  406. if (thread_count <= 1)
  407. scm_i_close_signal_pipe ();
  408. scm_i_pthread_mutex_unlock (&thread_admin_mutex);
  409. /* Although this thread has exited, the thread object might still be
  410. alive. Release unused memory. */
  411. t->freelists = NULL;
  412. t->pointerless_freelists = NULL;
  413. t->dynamic_state = NULL;
  414. t->dynstack.base = NULL;
  415. t->dynstack.top = NULL;
  416. t->dynstack.limit = NULL;
  417. scm_i_vm_free_stack (&t->vm);
  418. #if ENABLE_JIT
  419. scm_jit_state_free (t->jit_state);
  420. #endif
  421. t->jit_state = NULL;
  422. #ifdef SCM_HAVE_THREAD_STORAGE_CLASS
  423. scm_i_current_thread = NULL;
  424. #endif
  425. #if SCM_USE_PTHREAD_THREADS
  426. if (t->needs_unregister)
  427. GC_unregister_my_thread ();
  428. #endif
  429. }
  430. static scm_i_pthread_once_t init_thread_key_once = SCM_I_PTHREAD_ONCE_INIT;
  431. static void
  432. init_thread_key (void)
  433. {
  434. scm_i_pthread_key_create (&scm_i_thread_key, on_thread_exit);
  435. }
  436. /* Perform any initializations necessary to make the current thread
  437. known to Guile (via SCM_I_CURRENT_THREAD), initializing Guile itself,
  438. if necessary.
  439. BASE is the stack base to use with GC.
  440. DYNAMIC_STATE is the set of fluid values to start with.
  441. Returns zero when the thread was known to guile already; otherwise
  442. return 1.
  443. Note that it could be the case that the thread was known
  444. to Guile, but not in guile mode (because we are within a
  445. scm_without_guile call). Check SCM_I_CURRENT_THREAD->guile_mode to
  446. be sure. New threads are put into guile mode implicitly. */
  447. static int
  448. scm_i_init_thread_for_guile (struct GC_stack_base *base,
  449. SCM dynamic_state)
  450. {
  451. scm_i_pthread_once (&init_thread_key_once, init_thread_key);
  452. if (SCM_I_CURRENT_THREAD)
  453. {
  454. /* Thread is already known to Guile.
  455. */
  456. return 0;
  457. }
  458. else
  459. {
  460. /* This thread has not been guilified yet.
  461. */
  462. scm_i_pthread_mutex_lock (&scm_i_init_mutex);
  463. if (scm_initialized_p == 0)
  464. {
  465. /* First thread ever to enter Guile. Run the full
  466. initialization.
  467. */
  468. scm_i_init_guile (base);
  469. #if SCM_USE_PTHREAD_THREADS
  470. /* Allow other threads to come in later. */
  471. GC_allow_register_threads ();
  472. #endif
  473. scm_i_pthread_mutex_unlock (&scm_i_init_mutex);
  474. }
  475. else
  476. {
  477. int needs_unregister = 0;
  478. /* Guile is already initialized, but this thread enters it for
  479. the first time. Only initialize this thread.
  480. */
  481. scm_i_pthread_mutex_unlock (&scm_i_init_mutex);
  482. /* Register this thread with libgc. */
  483. #if SCM_USE_PTHREAD_THREADS
  484. if (GC_register_my_thread (base) == GC_SUCCESS)
  485. needs_unregister = 1;
  486. #endif
  487. guilify_self_1 (base, needs_unregister);
  488. guilify_self_2 (dynamic_state);
  489. }
  490. return 1;
  491. }
  492. }
  493. void
  494. scm_init_guile ()
  495. {
  496. struct GC_stack_base stack_base;
  497. if (GC_get_stack_base (&stack_base) == GC_SUCCESS)
  498. scm_i_init_thread_for_guile (&stack_base, default_dynamic_state);
  499. else
  500. {
  501. fprintf (stderr, "Failed to get stack base for current thread.\n");
  502. exit (EXIT_FAILURE);
  503. }
  504. }
  505. struct with_guile_args
  506. {
  507. GC_fn_type func;
  508. void *data;
  509. SCM dynamic_state;
  510. };
  511. static void *
  512. with_guile_trampoline (void *data)
  513. {
  514. struct with_guile_args *args = data;
  515. return scm_c_with_continuation_barrier (args->func, args->data);
  516. }
  517. static void *
  518. with_guile (struct GC_stack_base *base, void *data)
  519. {
  520. void *res;
  521. int new_thread;
  522. scm_thread *t;
  523. struct with_guile_args *args = data;
  524. new_thread = scm_i_init_thread_for_guile (base, args->dynamic_state);
  525. t = SCM_I_CURRENT_THREAD;
  526. if (new_thread)
  527. {
  528. /* We are in Guile mode. */
  529. assert (t->guile_mode);
  530. res = scm_c_with_continuation_barrier (args->func, args->data);
  531. /* Leave Guile mode. */
  532. t->guile_mode = 0;
  533. }
  534. else if (t->guile_mode)
  535. {
  536. /* Already in Guile mode. */
  537. res = scm_c_with_continuation_barrier (args->func, args->data);
  538. }
  539. else
  540. {
  541. /* We are not in Guile mode, either because we are not within a
  542. scm_with_guile, or because we are within a scm_without_guile.
  543. This call to scm_with_guile() could happen from anywhere on the
  544. stack, and in particular lower on the stack than when it was
  545. when this thread was first guilified. Thus, `base' must be
  546. updated. */
  547. #if SCM_STACK_GROWS_UP
  548. if (SCM_STACK_PTR (base->mem_base) < t->base)
  549. t->base = SCM_STACK_PTR (base->mem_base);
  550. #else
  551. if (SCM_STACK_PTR (base->mem_base) > t->base)
  552. t->base = SCM_STACK_PTR (base->mem_base);
  553. #endif
  554. t->guile_mode = 1;
  555. res = GC_call_with_gc_active (with_guile_trampoline, args);
  556. t->guile_mode = 0;
  557. }
  558. return res;
  559. }
  560. static void *
  561. scm_i_with_guile (void *(*func)(void *), void *data, SCM dynamic_state)
  562. {
  563. struct with_guile_args args;
  564. args.func = func;
  565. args.data = data;
  566. args.dynamic_state = dynamic_state;
  567. return GC_call_with_stack_base (with_guile, &args);
  568. }
  569. void *
  570. scm_with_guile (void *(*func)(void *), void *data)
  571. {
  572. return scm_i_with_guile (func, data, default_dynamic_state);
  573. }
  574. void *
  575. scm_without_guile (void *(*func)(void *), void *data)
  576. {
  577. void *result;
  578. scm_thread *t = SCM_I_CURRENT_THREAD;
  579. if (t->guile_mode)
  580. {
  581. SCM_I_CURRENT_THREAD->guile_mode = 0;
  582. result = GC_do_blocking (func, data);
  583. SCM_I_CURRENT_THREAD->guile_mode = 1;
  584. }
  585. else
  586. /* Otherwise we're not in guile mode, so nothing to do. */
  587. result = func (data);
  588. return result;
  589. }
  590. /*** Thread creation */
  591. /* Because (ice-9 boot-9) loads up (ice-9 threads), we know that this
  592. variable will get loaded before a call to scm_call_with_new_thread
  593. and therefore no lock or pthread_once_t is needed. */
  594. static SCM call_with_new_thread_var;
  595. SCM
  596. scm_call_with_new_thread (SCM thunk, SCM handler)
  597. {
  598. SCM call_with_new_thread = scm_variable_ref (call_with_new_thread_var);
  599. if (SCM_UNBNDP (handler))
  600. return scm_call_1 (call_with_new_thread, thunk);
  601. return scm_call_2 (call_with_new_thread, thunk, handler);
  602. }
  603. typedef struct launch_data launch_data;
  604. struct launch_data {
  605. launch_data *prev;
  606. launch_data *next;
  607. SCM dynamic_state;
  608. SCM thunk;
  609. };
  610. /* GC-protect the launch data for new threads. */
  611. static launch_data *protected_launch_data;
  612. static scm_i_pthread_mutex_t protected_launch_data_lock =
  613. SCM_I_PTHREAD_MUTEX_INITIALIZER;
  614. static void
  615. protect_launch_data (launch_data *data)
  616. {
  617. scm_i_pthread_mutex_lock (&protected_launch_data_lock);
  618. data->next = protected_launch_data;
  619. if (protected_launch_data)
  620. protected_launch_data->prev = data;
  621. protected_launch_data = data;
  622. scm_i_pthread_mutex_unlock (&protected_launch_data_lock);
  623. }
  624. static void
  625. unprotect_launch_data (launch_data *data)
  626. {
  627. scm_i_pthread_mutex_lock (&protected_launch_data_lock);
  628. if (data->next)
  629. data->next->prev = data->prev;
  630. if (data->prev)
  631. data->prev->next = data->next;
  632. else
  633. protected_launch_data = data->next;
  634. scm_i_pthread_mutex_unlock (&protected_launch_data_lock);
  635. }
  636. static void *
  637. really_launch (void *d)
  638. {
  639. scm_thread *t = SCM_I_CURRENT_THREAD;
  640. unprotect_launch_data (d);
  641. /* The thread starts with asyncs blocked. */
  642. t->block_asyncs++;
  643. SCM_I_CURRENT_THREAD->result = scm_call_0 (((launch_data *)d)->thunk);
  644. return 0;
  645. }
  646. static void *
  647. launch_thread (void *d)
  648. {
  649. launch_data *data = (launch_data *)d;
  650. scm_i_pthread_detach (scm_i_pthread_self ());
  651. scm_i_with_guile (really_launch, d, data->dynamic_state);
  652. return NULL;
  653. }
  654. SCM_INTERNAL SCM scm_sys_call_with_new_thread (SCM);
  655. SCM_DEFINE (scm_sys_call_with_new_thread, "%call-with-new-thread", 1, 0, 0,
  656. (SCM thunk), "")
  657. #define FUNC_NAME s_scm_sys_call_with_new_thread
  658. {
  659. launch_data *data;
  660. scm_i_pthread_t id;
  661. int err;
  662. SCM_ASSERT (scm_is_true (scm_thunk_p (thunk)), thunk, SCM_ARG1, FUNC_NAME);
  663. GC_collect_a_little ();
  664. data = scm_gc_typed_calloc (launch_data);
  665. data->dynamic_state = scm_current_dynamic_state ();
  666. data->thunk = thunk;
  667. protect_launch_data (data);
  668. err = scm_i_pthread_create (&id, NULL, launch_thread, data);
  669. if (err)
  670. {
  671. errno = err;
  672. scm_syserror (NULL);
  673. }
  674. return SCM_UNSPECIFIED;
  675. }
  676. #undef FUNC_NAME
  677. SCM
  678. scm_spawn_thread (scm_t_catch_body body, void *body_data,
  679. scm_t_catch_handler handler, void *handler_data)
  680. {
  681. SCM body_closure, handler_closure;
  682. body_closure = scm_i_make_catch_body_closure (body, body_data);
  683. handler_closure = handler == NULL ? SCM_UNDEFINED :
  684. scm_i_make_catch_handler_closure (handler, handler_data);
  685. return scm_call_with_new_thread (body_closure, handler_closure);
  686. }
  687. SCM_DEFINE (scm_yield, "yield", 0, 0, 0,
  688. (),
  689. "Move the calling thread to the end of the scheduling queue.")
  690. #define FUNC_NAME s_scm_yield
  691. {
  692. return scm_from_bool (scm_i_sched_yield ());
  693. }
  694. #undef FUNC_NAME
  695. static SCM cancel_thread_var;
  696. SCM
  697. scm_cancel_thread (SCM thread)
  698. {
  699. scm_call_1 (scm_variable_ref (cancel_thread_var), thread);
  700. return SCM_UNSPECIFIED;
  701. }
  702. static SCM join_thread_var;
  703. SCM
  704. scm_join_thread (SCM thread)
  705. {
  706. return scm_call_1 (scm_variable_ref (join_thread_var), thread);
  707. }
  708. SCM
  709. scm_join_thread_timed (SCM thread, SCM timeout, SCM timeoutval)
  710. {
  711. SCM join_thread = scm_variable_ref (join_thread_var);
  712. if (SCM_UNBNDP (timeout))
  713. return scm_call_1 (join_thread, thread);
  714. else if (SCM_UNBNDP (timeoutval))
  715. return scm_call_2 (join_thread, thread, timeout);
  716. else
  717. return scm_call_3 (join_thread, thread, timeout, timeoutval);
  718. }
  719. SCM_DEFINE (scm_thread_p, "thread?", 1, 0, 0,
  720. (SCM obj),
  721. "Return @code{#t} if @var{obj} is a thread.")
  722. #define FUNC_NAME s_scm_thread_p
  723. {
  724. return SCM_I_IS_THREAD(obj) ? SCM_BOOL_T : SCM_BOOL_F;
  725. }
  726. #undef FUNC_NAME
  727. /* We implement our own mutex type since we want them to be 'fair', we
  728. want to do fancy things while waiting for them (like running
  729. asyncs) and we might want to add things that are nice for
  730. debugging.
  731. */
  732. enum scm_mutex_kind {
  733. /* A standard mutex can only be locked once. If you try to lock it
  734. again from the thread that locked it to begin with (the "owner"
  735. thread), it throws an error. It can only be unlocked from the
  736. thread that locked it in the first place. */
  737. SCM_MUTEX_STANDARD,
  738. /* A recursive mutex can be locked multiple times by its owner. It
  739. then has to be unlocked the corresponding number of times, and like
  740. standard mutexes can only be unlocked by the owner thread. */
  741. SCM_MUTEX_RECURSIVE,
  742. /* An unowned mutex is like a standard mutex, except that it can be
  743. unlocked by any thread. A corrolary of this behavior is that a
  744. thread's attempt to lock a mutex that it already owns will block
  745. instead of signalling an error, as it could be that some other
  746. thread unlocks the mutex, allowing the owner thread to proceed.
  747. This kind of mutex is a bit strange and is here for use by
  748. SRFI-18. */
  749. SCM_MUTEX_UNOWNED
  750. };
  751. struct scm_mutex {
  752. scm_i_pthread_mutex_t lock;
  753. /* The thread that owns this mutex, or #f if the mutex is unlocked. */
  754. SCM owner;
  755. /* Queue of threads waiting for this mutex. */
  756. SCM waiting;
  757. /* For SCM_MUTEX_RECURSIVE (and only SCM_MUTEX_RECURSIVE), the
  758. recursive lock count. The first lock does not count. */
  759. int level;
  760. };
  761. #define SCM_MUTEXP(x) SCM_SMOB_PREDICATE (scm_tc16_mutex, x)
  762. #define SCM_MUTEX_DATA(x) ((struct scm_mutex *) SCM_SMOB_DATA (x))
  763. #define SCM_MUTEX_KIND(x) ((enum scm_mutex_kind) (SCM_SMOB_FLAGS (x) & 0x3))
  764. static int
  765. scm_mutex_print (SCM mx, SCM port, scm_print_state *pstate SCM_UNUSED)
  766. {
  767. struct scm_mutex *m = SCM_MUTEX_DATA (mx);
  768. scm_puts ("#<mutex ", port);
  769. scm_uintprint ((scm_t_bits)m, 16, port);
  770. scm_puts (">", port);
  771. return 1;
  772. }
  773. SCM_SYMBOL (allow_external_unlock_sym, "allow-external-unlock");
  774. SCM_SYMBOL (recursive_sym, "recursive");
  775. SCM_DEFINE (scm_make_mutex_with_kind, "make-mutex", 0, 1, 0,
  776. (SCM kind),
  777. "Create a new mutex. If @var{kind} is not given, the mutex\n"
  778. "will be a standard non-recursive mutex. Otherwise pass\n"
  779. "@code{recursive} to make a recursive mutex, or\n"
  780. "@code{allow-external-unlock} to make a non-recursive mutex\n"
  781. "that can be unlocked from any thread.")
  782. #define FUNC_NAME s_scm_make_mutex_with_kind
  783. {
  784. enum scm_mutex_kind mkind = SCM_MUTEX_STANDARD;
  785. struct scm_mutex *m;
  786. scm_i_pthread_mutex_t lock = SCM_I_PTHREAD_MUTEX_INITIALIZER;
  787. if (!SCM_UNBNDP (kind))
  788. {
  789. if (scm_is_eq (kind, allow_external_unlock_sym))
  790. mkind = SCM_MUTEX_UNOWNED;
  791. else if (scm_is_eq (kind, recursive_sym))
  792. mkind = SCM_MUTEX_RECURSIVE;
  793. else
  794. SCM_MISC_ERROR ("unsupported mutex kind: ~a", scm_list_1 (kind));
  795. }
  796. m = scm_gc_malloc (sizeof (struct scm_mutex), "mutex");
  797. /* Because PTHREAD_MUTEX_INITIALIZER is static, it's plain old data,
  798. and so we can just copy it. */
  799. memcpy (&m->lock, &lock, sizeof (m->lock));
  800. m->owner = SCM_BOOL_F;
  801. m->level = 0;
  802. m->waiting = make_queue ();
  803. return scm_new_smob (scm_tc16_mutex | (mkind << 16), (scm_t_bits) m);
  804. }
  805. #undef FUNC_NAME
  806. SCM
  807. scm_make_mutex (void)
  808. {
  809. return scm_make_mutex_with_kind (SCM_UNDEFINED);
  810. }
  811. SCM_DEFINE (scm_make_recursive_mutex, "make-recursive-mutex", 0, 0, 0,
  812. (void),
  813. "Create a new recursive mutex. ")
  814. #define FUNC_NAME s_scm_make_recursive_mutex
  815. {
  816. return scm_make_mutex_with_kind (recursive_sym);
  817. }
  818. #undef FUNC_NAME
  819. SCM
  820. scm_lock_mutex (SCM mx)
  821. {
  822. return scm_timed_lock_mutex (mx, SCM_UNDEFINED);
  823. }
  824. static inline SCM
  825. lock_mutex (enum scm_mutex_kind kind, struct scm_mutex *m,
  826. scm_thread *current_thread, scm_t_timespec *waittime)
  827. #define FUNC_NAME "lock-mutex"
  828. {
  829. scm_i_scm_pthread_mutex_lock (&m->lock);
  830. if (scm_is_eq (m->owner, SCM_BOOL_F))
  831. {
  832. m->owner = current_thread->handle;
  833. scm_i_pthread_mutex_unlock (&m->lock);
  834. return SCM_BOOL_T;
  835. }
  836. else if (kind == SCM_MUTEX_RECURSIVE &&
  837. scm_is_eq (m->owner, current_thread->handle))
  838. {
  839. m->level++;
  840. scm_i_pthread_mutex_unlock (&m->lock);
  841. return SCM_BOOL_T;
  842. }
  843. else if (kind == SCM_MUTEX_STANDARD &&
  844. scm_is_eq (m->owner, current_thread->handle))
  845. {
  846. scm_i_pthread_mutex_unlock (&m->lock);
  847. SCM_MISC_ERROR ("mutex already locked by thread", SCM_EOL);
  848. }
  849. else
  850. while (1)
  851. {
  852. int err = block_self (m->waiting, &m->lock, waittime);
  853. if (err == 0)
  854. {
  855. if (scm_is_eq (m->owner, SCM_BOOL_F))
  856. {
  857. m->owner = current_thread->handle;
  858. scm_i_pthread_mutex_unlock (&m->lock);
  859. return SCM_BOOL_T;
  860. }
  861. else
  862. continue;
  863. }
  864. else if (err == ETIMEDOUT)
  865. {
  866. scm_i_pthread_mutex_unlock (&m->lock);
  867. return SCM_BOOL_F;
  868. }
  869. else if (err == EINTR)
  870. {
  871. scm_i_pthread_mutex_unlock (&m->lock);
  872. scm_async_tick ();
  873. scm_i_scm_pthread_mutex_lock (&m->lock);
  874. continue;
  875. }
  876. else
  877. {
  878. /* Shouldn't happen. */
  879. scm_i_pthread_mutex_unlock (&m->lock);
  880. errno = err;
  881. SCM_SYSERROR;
  882. }
  883. }
  884. }
  885. #undef FUNC_NAME
  886. SCM_DEFINE (scm_timed_lock_mutex, "lock-mutex", 1, 1, 0,
  887. (SCM mutex, SCM timeout),
  888. "Lock mutex @var{mutex}. If the mutex is already locked, "
  889. "the calling thread blocks until the mutex becomes available.")
  890. #define FUNC_NAME s_scm_timed_lock_mutex
  891. {
  892. scm_t_timespec cwaittime, *waittime = NULL;
  893. struct scm_mutex *m;
  894. scm_thread *t = SCM_I_CURRENT_THREAD;
  895. SCM ret;
  896. SCM_VALIDATE_MUTEX (1, mutex);
  897. m = SCM_MUTEX_DATA (mutex);
  898. if (! SCM_UNBNDP (timeout) && ! scm_is_false (timeout))
  899. {
  900. to_timespec (timeout, &cwaittime);
  901. waittime = &cwaittime;
  902. }
  903. /* Specialized lock_mutex implementations according to the mutex
  904. kind. */
  905. switch (SCM_MUTEX_KIND (mutex))
  906. {
  907. case SCM_MUTEX_STANDARD:
  908. ret = lock_mutex (SCM_MUTEX_STANDARD, m, t, waittime);
  909. break;
  910. case SCM_MUTEX_RECURSIVE:
  911. ret = lock_mutex (SCM_MUTEX_RECURSIVE, m, t, waittime);
  912. break;
  913. case SCM_MUTEX_UNOWNED:
  914. ret = lock_mutex (SCM_MUTEX_UNOWNED, m, t, waittime);
  915. break;
  916. default:
  917. abort ();
  918. }
  919. scm_remember_upto_here_1 (mutex);
  920. return ret;
  921. }
  922. #undef FUNC_NAME
  923. static void
  924. lock_mutex_return_void (SCM mx)
  925. {
  926. (void) scm_lock_mutex (mx);
  927. }
  928. static void
  929. unlock_mutex_return_void (SCM mx)
  930. {
  931. (void) scm_unlock_mutex (mx);
  932. }
  933. void
  934. scm_dynwind_lock_mutex (SCM mutex)
  935. {
  936. scm_dynwind_unwind_handler_with_scm (unlock_mutex_return_void, mutex,
  937. SCM_F_WIND_EXPLICITLY);
  938. scm_dynwind_rewind_handler_with_scm (lock_mutex_return_void, mutex,
  939. SCM_F_WIND_EXPLICITLY);
  940. }
  941. SCM
  942. scm_try_mutex (SCM mutex)
  943. {
  944. return scm_timed_lock_mutex (mutex, SCM_INUM0);
  945. }
  946. /* This function is static inline so that the compiler can specialize it
  947. against the mutex kind. */
  948. static inline void
  949. unlock_mutex (enum scm_mutex_kind kind, struct scm_mutex *m,
  950. scm_thread *current_thread)
  951. #define FUNC_NAME "unlock-mutex"
  952. {
  953. scm_i_scm_pthread_mutex_lock (&m->lock);
  954. if (!scm_is_eq (m->owner, current_thread->handle))
  955. {
  956. if (scm_is_eq (m->owner, SCM_BOOL_F))
  957. {
  958. scm_i_pthread_mutex_unlock (&m->lock);
  959. SCM_MISC_ERROR ("mutex not locked", SCM_EOL);
  960. }
  961. if (kind != SCM_MUTEX_UNOWNED)
  962. {
  963. scm_i_pthread_mutex_unlock (&m->lock);
  964. SCM_MISC_ERROR ("mutex not locked by current thread", SCM_EOL);
  965. }
  966. }
  967. if (kind == SCM_MUTEX_RECURSIVE && m->level > 0)
  968. m->level--;
  969. else
  970. {
  971. m->owner = SCM_BOOL_F;
  972. /* Wake up one waiter. */
  973. unblock_from_queue (m->waiting);
  974. }
  975. scm_i_pthread_mutex_unlock (&m->lock);
  976. }
  977. #undef FUNC_NAME
  978. SCM_DEFINE (scm_unlock_mutex, "unlock-mutex", 1, 0, 0, (SCM mutex),
  979. "Unlocks @var{mutex}. The calling thread must already hold\n"
  980. "the lock on @var{mutex}, unless the mutex was created with\n"
  981. "the @code{allow-external-unlock} option; otherwise an error\n"
  982. "will be signalled.")
  983. #define FUNC_NAME s_scm_unlock_mutex
  984. {
  985. struct scm_mutex *m;
  986. scm_thread *t = SCM_I_CURRENT_THREAD;
  987. SCM_VALIDATE_MUTEX (1, mutex);
  988. m = SCM_MUTEX_DATA (mutex);
  989. /* Specialized unlock_mutex implementations according to the mutex
  990. kind. */
  991. switch (SCM_MUTEX_KIND (mutex))
  992. {
  993. case SCM_MUTEX_STANDARD:
  994. unlock_mutex (SCM_MUTEX_STANDARD, m, t);
  995. break;
  996. case SCM_MUTEX_RECURSIVE:
  997. unlock_mutex (SCM_MUTEX_RECURSIVE, m, t);
  998. break;
  999. case SCM_MUTEX_UNOWNED:
  1000. unlock_mutex (SCM_MUTEX_UNOWNED, m, t);
  1001. break;
  1002. default:
  1003. abort ();
  1004. }
  1005. scm_remember_upto_here_1 (mutex);
  1006. return SCM_BOOL_T;
  1007. }
  1008. #undef FUNC_NAME
  1009. SCM_DEFINE (scm_mutex_p, "mutex?", 1, 0, 0,
  1010. (SCM obj),
  1011. "Return @code{#t} if @var{obj} is a mutex.")
  1012. #define FUNC_NAME s_scm_mutex_p
  1013. {
  1014. return SCM_MUTEXP (obj) ? SCM_BOOL_T : SCM_BOOL_F;
  1015. }
  1016. #undef FUNC_NAME
  1017. SCM_DEFINE (scm_mutex_owner, "mutex-owner", 1, 0, 0,
  1018. (SCM mx),
  1019. "Return the thread owning @var{mx}, or @code{#f}.")
  1020. #define FUNC_NAME s_scm_mutex_owner
  1021. {
  1022. SCM owner;
  1023. struct scm_mutex *m = NULL;
  1024. SCM_VALIDATE_MUTEX (1, mx);
  1025. m = SCM_MUTEX_DATA (mx);
  1026. scm_i_pthread_mutex_lock (&m->lock);
  1027. owner = m->owner;
  1028. scm_i_pthread_mutex_unlock (&m->lock);
  1029. return owner;
  1030. }
  1031. #undef FUNC_NAME
  1032. SCM_DEFINE (scm_mutex_level, "mutex-level", 1, 0, 0,
  1033. (SCM mx),
  1034. "Return the lock level of mutex @var{mx}.")
  1035. #define FUNC_NAME s_scm_mutex_level
  1036. {
  1037. SCM_VALIDATE_MUTEX (1, mx);
  1038. if (SCM_MUTEX_KIND (mx) == SCM_MUTEX_RECURSIVE)
  1039. return scm_from_int (SCM_MUTEX_DATA (mx)->level + 1);
  1040. else if (scm_is_eq (SCM_MUTEX_DATA (mx)->owner, SCM_BOOL_F))
  1041. return SCM_INUM0;
  1042. else
  1043. return SCM_INUM1;
  1044. }
  1045. #undef FUNC_NAME
  1046. SCM_DEFINE (scm_mutex_locked_p, "mutex-locked?", 1, 0, 0,
  1047. (SCM mx),
  1048. "Returns @code{#t} if the mutex @var{mx} is locked.")
  1049. #define FUNC_NAME s_scm_mutex_locked_p
  1050. {
  1051. SCM_VALIDATE_MUTEX (1, mx);
  1052. if (scm_is_eq (SCM_MUTEX_DATA (mx)->owner, SCM_BOOL_F))
  1053. return SCM_BOOL_F;
  1054. else
  1055. return SCM_BOOL_T;
  1056. }
  1057. #undef FUNC_NAME
  1058. struct scm_cond {
  1059. scm_i_pthread_mutex_t lock;
  1060. SCM waiting; /* the threads waiting for this condition. */
  1061. };
  1062. #define SCM_CONDVARP(x) SCM_SMOB_PREDICATE (scm_tc16_condvar, x)
  1063. #define SCM_CONDVAR_DATA(x) ((struct scm_cond *) SCM_SMOB_DATA (x))
  1064. static int
  1065. scm_cond_print (SCM cv, SCM port, scm_print_state *pstate SCM_UNUSED)
  1066. {
  1067. struct scm_cond *c = SCM_CONDVAR_DATA (cv);
  1068. scm_puts ("#<condition-variable ", port);
  1069. scm_uintprint ((scm_t_bits)c, 16, port);
  1070. scm_puts (">", port);
  1071. return 1;
  1072. }
  1073. SCM_DEFINE (scm_make_condition_variable, "make-condition-variable", 0, 0, 0,
  1074. (void),
  1075. "Make a new condition variable.")
  1076. #define FUNC_NAME s_scm_make_condition_variable
  1077. {
  1078. struct scm_cond *c;
  1079. SCM cv;
  1080. c = scm_gc_malloc (sizeof (struct scm_cond), "condition variable");
  1081. c->waiting = SCM_EOL;
  1082. SCM_NEWSMOB (cv, scm_tc16_condvar, (scm_t_bits) c);
  1083. c->waiting = make_queue ();
  1084. return cv;
  1085. }
  1086. #undef FUNC_NAME
  1087. static inline SCM
  1088. timed_wait (enum scm_mutex_kind kind, struct scm_mutex *m, struct scm_cond *c,
  1089. scm_thread *current_thread, scm_t_timespec *waittime)
  1090. #define FUNC_NAME "wait-condition-variable"
  1091. {
  1092. scm_i_scm_pthread_mutex_lock (&m->lock);
  1093. if (!scm_is_eq (m->owner, current_thread->handle))
  1094. {
  1095. if (scm_is_eq (m->owner, SCM_BOOL_F))
  1096. {
  1097. scm_i_pthread_mutex_unlock (&m->lock);
  1098. SCM_MISC_ERROR ("mutex not locked", SCM_EOL);
  1099. }
  1100. if (kind != SCM_MUTEX_UNOWNED)
  1101. {
  1102. scm_i_pthread_mutex_unlock (&m->lock);
  1103. SCM_MISC_ERROR ("mutex not locked by current thread", SCM_EOL);
  1104. }
  1105. }
  1106. while (1)
  1107. {
  1108. int err = 0;
  1109. /* Unlock the mutex. */
  1110. if (kind == SCM_MUTEX_RECURSIVE && m->level > 0)
  1111. m->level--;
  1112. else
  1113. {
  1114. m->owner = SCM_BOOL_F;
  1115. /* Wake up one waiter. */
  1116. unblock_from_queue (m->waiting);
  1117. }
  1118. /* Wait for someone to signal the cond, a timeout, or an
  1119. interrupt. */
  1120. err = block_self (c->waiting, &m->lock, waittime);
  1121. /* We woke up for some reason. Reacquire the mutex before doing
  1122. anything else.
  1123. FIXME: We disable interrupts while reacquiring the mutex. If
  1124. we allow interrupts here, there's the risk of a nonlocal exit
  1125. before we reaquire the mutex, which would be visible to user
  1126. code.
  1127. For example the unwind handler in
  1128. (with-mutex m (wait-condition-variable c m))
  1129. that tries to unlock M could see M in an already-unlocked
  1130. state, if an interrupt while waiting on C caused the wait to
  1131. abort and the woke thread lost the race to reacquire M. That's
  1132. not great. Maybe it's necessary but for now we just disable
  1133. interrupts while reaquiring a mutex after a wait. */
  1134. current_thread->block_asyncs++;
  1135. if (kind == SCM_MUTEX_RECURSIVE &&
  1136. scm_is_eq (m->owner, current_thread->handle))
  1137. {
  1138. m->level++;
  1139. scm_i_pthread_mutex_unlock (&m->lock);
  1140. }
  1141. else
  1142. while (1)
  1143. {
  1144. if (scm_is_eq (m->owner, SCM_BOOL_F))
  1145. {
  1146. m->owner = current_thread->handle;
  1147. scm_i_pthread_mutex_unlock (&m->lock);
  1148. break;
  1149. }
  1150. block_self (m->waiting, &m->lock, waittime);
  1151. }
  1152. current_thread->block_asyncs--;
  1153. /* Now that we have the mutex again, handle the return value. */
  1154. if (err == 0)
  1155. return SCM_BOOL_T;
  1156. else if (err == ETIMEDOUT)
  1157. return SCM_BOOL_F;
  1158. else if (err == EINTR)
  1159. /* Let caller run scm_async_tick() and loop. */
  1160. return SCM_BOOL_T;
  1161. else
  1162. {
  1163. /* Shouldn't happen. */
  1164. errno = err;
  1165. SCM_SYSERROR;
  1166. }
  1167. }
  1168. }
  1169. #undef FUNC_NAME
  1170. SCM_DEFINE (scm_timed_wait_condition_variable, "wait-condition-variable", 2, 1, 0,
  1171. (SCM cond, SCM mutex, SCM timeout),
  1172. "Wait until condition variable @var{cv} has been signalled. While waiting, "
  1173. "mutex @var{mx} is atomically unlocked (as with @code{unlock-mutex}) and "
  1174. "is locked again when this function returns. When @var{t} is given, "
  1175. "it specifies a point in time where the waiting should be aborted. It "
  1176. "can be either a integer as returned by @code{current-time} or a pair "
  1177. "as returned by @code{gettimeofday}. When the waiting is aborted the "
  1178. "mutex is locked and @code{#f} is returned. When the condition "
  1179. "variable is in fact signalled, the mutex is also locked and @code{#t} "
  1180. "is returned. ")
  1181. #define FUNC_NAME s_scm_timed_wait_condition_variable
  1182. {
  1183. scm_t_timespec waittime_val, *waittime = NULL;
  1184. struct scm_cond *c;
  1185. struct scm_mutex *m;
  1186. scm_thread *t = SCM_I_CURRENT_THREAD;
  1187. SCM ret;
  1188. SCM_VALIDATE_CONDVAR (1, cond);
  1189. SCM_VALIDATE_MUTEX (2, mutex);
  1190. c = SCM_CONDVAR_DATA (cond);
  1191. m = SCM_MUTEX_DATA (mutex);
  1192. if (!SCM_UNBNDP (timeout))
  1193. {
  1194. to_timespec (timeout, &waittime_val);
  1195. waittime = &waittime_val;
  1196. }
  1197. /* Specialized timed_wait implementations according to the mutex
  1198. kind. */
  1199. switch (SCM_MUTEX_KIND (mutex))
  1200. {
  1201. case SCM_MUTEX_STANDARD:
  1202. ret = timed_wait (SCM_MUTEX_STANDARD, m, c, t, waittime);
  1203. break;
  1204. case SCM_MUTEX_RECURSIVE:
  1205. ret = timed_wait (SCM_MUTEX_RECURSIVE, m, c, t, waittime);
  1206. break;
  1207. case SCM_MUTEX_UNOWNED:
  1208. ret = timed_wait (SCM_MUTEX_UNOWNED, m, c, t, waittime);
  1209. break;
  1210. default:
  1211. abort ();
  1212. }
  1213. scm_remember_upto_here_2 (mutex, cond);
  1214. return ret;
  1215. }
  1216. #undef FUNC_NAME
  1217. SCM_DEFINE (scm_signal_condition_variable, "signal-condition-variable", 1, 0, 0,
  1218. (SCM cv),
  1219. "Wake up one thread that is waiting for @var{cv}")
  1220. #define FUNC_NAME s_scm_signal_condition_variable
  1221. {
  1222. struct scm_cond *c;
  1223. SCM_VALIDATE_CONDVAR (1, cv);
  1224. c = SCM_CONDVAR_DATA (cv);
  1225. unblock_from_queue (c->waiting);
  1226. return SCM_BOOL_T;
  1227. }
  1228. #undef FUNC_NAME
  1229. SCM_DEFINE (scm_broadcast_condition_variable, "broadcast-condition-variable", 1, 0, 0,
  1230. (SCM cv),
  1231. "Wake up all threads that are waiting for @var{cv}. ")
  1232. #define FUNC_NAME s_scm_broadcast_condition_variable
  1233. {
  1234. struct scm_cond *c;
  1235. SCM_VALIDATE_CONDVAR (1, cv);
  1236. c = SCM_CONDVAR_DATA (cv);
  1237. while (scm_is_true (unblock_from_queue (c->waiting)))
  1238. ;
  1239. return SCM_BOOL_T;
  1240. }
  1241. #undef FUNC_NAME
  1242. SCM_DEFINE (scm_condition_variable_p, "condition-variable?", 1, 0, 0,
  1243. (SCM obj),
  1244. "Return @code{#t} if @var{obj} is a condition variable.")
  1245. #define FUNC_NAME s_scm_condition_variable_p
  1246. {
  1247. return SCM_CONDVARP(obj) ? SCM_BOOL_T : SCM_BOOL_F;
  1248. }
  1249. #undef FUNC_NAME
  1250. /*** Select */
  1251. struct select_args
  1252. {
  1253. int nfds;
  1254. fd_set *read_fds;
  1255. fd_set *write_fds;
  1256. fd_set *except_fds;
  1257. struct timeval *timeout;
  1258. int result;
  1259. int errno_value;
  1260. };
  1261. static void *
  1262. do_std_select (void *args)
  1263. {
  1264. struct select_args *select_args;
  1265. select_args = (struct select_args *) args;
  1266. select_args->result =
  1267. select (select_args->nfds,
  1268. select_args->read_fds, select_args->write_fds,
  1269. select_args->except_fds, select_args->timeout);
  1270. select_args->errno_value = errno;
  1271. return NULL;
  1272. }
  1273. int
  1274. scm_std_select (int nfds,
  1275. fd_set *readfds,
  1276. fd_set *writefds,
  1277. fd_set *exceptfds,
  1278. struct timeval *timeout)
  1279. {
  1280. fd_set my_readfds;
  1281. int res, eno, wakeup_fd;
  1282. scm_thread *t = SCM_I_CURRENT_THREAD;
  1283. struct select_args args;
  1284. if (readfds == NULL)
  1285. {
  1286. FD_ZERO (&my_readfds);
  1287. readfds = &my_readfds;
  1288. }
  1289. if (scm_i_prepare_to_wait_on_fd (t, t->sleep_pipe[1]))
  1290. {
  1291. eno = EINTR;
  1292. res = -1;
  1293. }
  1294. else
  1295. {
  1296. wakeup_fd = t->sleep_pipe[0];
  1297. FD_SET (wakeup_fd, readfds);
  1298. if (wakeup_fd >= nfds)
  1299. nfds = wakeup_fd+1;
  1300. args.nfds = nfds;
  1301. args.read_fds = readfds;
  1302. args.write_fds = writefds;
  1303. args.except_fds = exceptfds;
  1304. args.timeout = timeout;
  1305. /* Explicitly cooperate with the GC. */
  1306. scm_without_guile (do_std_select, &args);
  1307. res = args.result;
  1308. eno = args.errno_value;
  1309. scm_i_wait_finished (t);
  1310. if (res > 0 && FD_ISSET (wakeup_fd, readfds))
  1311. {
  1312. char dummy;
  1313. full_read (wakeup_fd, &dummy, 1);
  1314. FD_CLR (wakeup_fd, readfds);
  1315. res -= 1;
  1316. if (res == 0)
  1317. {
  1318. eno = EINTR;
  1319. res = -1;
  1320. }
  1321. }
  1322. }
  1323. errno = eno;
  1324. return res;
  1325. }
  1326. /* Convenience API for blocking while in guile mode. */
  1327. #if SCM_USE_PTHREAD_THREADS
  1328. /* It seems reasonable to not run procedures related to mutex and condition
  1329. variables within `GC_do_blocking ()' since, (i) the GC can operate even
  1330. without it, and (ii) the only potential gain would be GC latency. See
  1331. http://thread.gmane.org/gmane.comp.programming.garbage-collection.boehmgc/2245/focus=2251
  1332. for a discussion of the pros and cons. */
  1333. int
  1334. scm_pthread_mutex_lock (scm_i_pthread_mutex_t *mutex)
  1335. {
  1336. int res = scm_i_pthread_mutex_lock (mutex);
  1337. return res;
  1338. }
  1339. static void
  1340. do_unlock (void *data)
  1341. {
  1342. scm_i_pthread_mutex_unlock ((scm_i_pthread_mutex_t *)data);
  1343. }
  1344. void
  1345. scm_dynwind_pthread_mutex_lock (scm_i_pthread_mutex_t *mutex)
  1346. {
  1347. scm_i_scm_pthread_mutex_lock (mutex);
  1348. scm_dynwind_unwind_handler (do_unlock, mutex, SCM_F_WIND_EXPLICITLY);
  1349. }
  1350. int
  1351. scm_pthread_cond_wait (scm_i_pthread_cond_t *cond, scm_i_pthread_mutex_t *mutex)
  1352. {
  1353. return scm_i_pthread_cond_wait (cond, mutex);
  1354. }
  1355. int
  1356. scm_pthread_cond_timedwait (scm_i_pthread_cond_t *cond,
  1357. scm_i_pthread_mutex_t *mutex,
  1358. const scm_t_timespec *wt)
  1359. {
  1360. return scm_i_pthread_cond_timedwait (cond, mutex, wt);
  1361. }
  1362. #endif
  1363. static void
  1364. do_unlock_with_asyncs (void *data)
  1365. {
  1366. scm_i_pthread_mutex_unlock ((scm_i_pthread_mutex_t *)data);
  1367. SCM_I_CURRENT_THREAD->block_asyncs--;
  1368. }
  1369. void
  1370. scm_i_dynwind_pthread_mutex_lock_block_asyncs (scm_i_pthread_mutex_t *mutex)
  1371. {
  1372. SCM_I_CURRENT_THREAD->block_asyncs++;
  1373. scm_i_scm_pthread_mutex_lock (mutex);
  1374. scm_dynwind_unwind_handler (do_unlock_with_asyncs, mutex,
  1375. SCM_F_WIND_EXPLICITLY);
  1376. }
  1377. unsigned long
  1378. scm_std_usleep (unsigned long usecs)
  1379. {
  1380. struct timeval tv;
  1381. tv.tv_usec = usecs % 1000000;
  1382. tv.tv_sec = usecs / 1000000;
  1383. scm_std_select (0, NULL, NULL, NULL, &tv);
  1384. return tv.tv_sec * 1000000 + tv.tv_usec;
  1385. }
  1386. unsigned int
  1387. scm_std_sleep (unsigned int secs)
  1388. {
  1389. struct timeval tv;
  1390. tv.tv_usec = 0;
  1391. tv.tv_sec = secs;
  1392. scm_std_select (0, NULL, NULL, NULL, &tv);
  1393. return tv.tv_sec;
  1394. }
  1395. /*** Misc */
  1396. SCM_DEFINE (scm_current_thread, "current-thread", 0, 0, 0,
  1397. (void),
  1398. "Return the thread that called this function.")
  1399. #define FUNC_NAME s_scm_current_thread
  1400. {
  1401. return SCM_I_CURRENT_THREAD->handle;
  1402. }
  1403. #undef FUNC_NAME
  1404. static SCM
  1405. scm_c_make_list (size_t n, SCM fill)
  1406. {
  1407. SCM res = SCM_EOL;
  1408. while (n-- > 0)
  1409. res = scm_cons (fill, res);
  1410. return res;
  1411. }
  1412. SCM_DEFINE (scm_all_threads, "all-threads", 0, 0, 0,
  1413. (void),
  1414. "Return a list of all threads.")
  1415. #define FUNC_NAME s_scm_all_threads
  1416. {
  1417. /* We can not allocate while holding the thread_admin_mutex because
  1418. of the way GC is done.
  1419. */
  1420. int n = thread_count;
  1421. scm_thread *t;
  1422. SCM list = scm_c_make_list (n, SCM_UNSPECIFIED), *l;
  1423. scm_i_pthread_mutex_lock (&thread_admin_mutex);
  1424. l = &list;
  1425. for (t = all_threads; t && n > 0; t = t->next_thread)
  1426. {
  1427. if (t != scm_i_signal_delivery_thread)
  1428. {
  1429. SCM_SETCAR (*l, t->handle);
  1430. l = SCM_CDRLOC (*l);
  1431. }
  1432. n--;
  1433. }
  1434. *l = SCM_EOL;
  1435. scm_i_pthread_mutex_unlock (&thread_admin_mutex);
  1436. return list;
  1437. }
  1438. #undef FUNC_NAME
  1439. SCM_DEFINE (scm_thread_exited_p, "thread-exited?", 1, 0, 0,
  1440. (SCM thread),
  1441. "Return @code{#t} iff @var{thread} has exited.\n")
  1442. #define FUNC_NAME s_scm_thread_exited_p
  1443. {
  1444. return scm_from_bool (scm_c_thread_exited_p (thread));
  1445. }
  1446. #undef FUNC_NAME
  1447. int
  1448. scm_c_thread_exited_p (SCM thread)
  1449. #define FUNC_NAME s_scm_thread_exited_p
  1450. {
  1451. scm_thread *t;
  1452. SCM_VALIDATE_THREAD (1, thread);
  1453. t = SCM_I_THREAD_DATA (thread);
  1454. return t->exited;
  1455. }
  1456. #undef FUNC_NAME
  1457. SCM_DEFINE (scm_total_processor_count, "total-processor-count", 0, 0, 0,
  1458. (void),
  1459. "Return the total number of processors of the machine, which\n"
  1460. "is guaranteed to be at least 1. A ``processor'' here is a\n"
  1461. "thread execution unit, which can be either:\n\n"
  1462. "@itemize\n"
  1463. "@item an execution core in a (possibly multi-core) chip, in a\n"
  1464. " (possibly multi- chip) module, in a single computer, or\n"
  1465. "@item a thread execution unit inside a core in the case of\n"
  1466. " @dfn{hyper-threaded} CPUs.\n"
  1467. "@end itemize\n\n"
  1468. "Which of the two definitions is used, is unspecified.\n")
  1469. #define FUNC_NAME s_scm_total_processor_count
  1470. {
  1471. return scm_from_ulong (num_processors (NPROC_ALL));
  1472. }
  1473. #undef FUNC_NAME
  1474. SCM_DEFINE (scm_current_processor_count, "current-processor-count", 0, 0, 0,
  1475. (void),
  1476. "Like @code{total-processor-count}, but return the number of\n"
  1477. "processors available to the current process. See\n"
  1478. "@code{setaffinity} and @code{getaffinity} for more\n"
  1479. "information.\n")
  1480. #define FUNC_NAME s_scm_current_processor_count
  1481. {
  1482. return scm_from_ulong (num_processors (NPROC_CURRENT));
  1483. }
  1484. #undef FUNC_NAME
  1485. static scm_i_pthread_cond_t wake_up_cond;
  1486. static int threads_initialized_p = 0;
  1487. /*** Initialization */
  1488. scm_i_pthread_mutex_t scm_i_misc_mutex;
  1489. #if SCM_USE_PTHREAD_THREADS
  1490. pthread_mutexattr_t scm_i_pthread_mutexattr_recursive[1];
  1491. #endif
  1492. void
  1493. scm_threads_prehistory (void *base)
  1494. {
  1495. #if SCM_USE_PTHREAD_THREADS
  1496. pthread_mutexattr_init (scm_i_pthread_mutexattr_recursive);
  1497. pthread_mutexattr_settype (scm_i_pthread_mutexattr_recursive,
  1498. PTHREAD_MUTEX_RECURSIVE);
  1499. #endif
  1500. scm_i_pthread_mutex_init (&scm_i_misc_mutex, NULL);
  1501. scm_i_pthread_cond_init (&wake_up_cond, NULL);
  1502. thread_gc_kind =
  1503. GC_new_kind (GC_new_free_list (),
  1504. GC_MAKE_PROC (GC_new_proc (thread_mark), 0),
  1505. 0, 1);
  1506. guilify_self_1 ((struct GC_stack_base *) base, 0);
  1507. }
  1508. scm_t_bits scm_tc16_thread;
  1509. scm_t_bits scm_tc16_mutex;
  1510. scm_t_bits scm_tc16_condvar;
  1511. static void
  1512. scm_init_ice_9_threads (void *unused)
  1513. {
  1514. #include "threads.x"
  1515. cancel_thread_var =
  1516. scm_module_variable (scm_current_module (),
  1517. scm_from_latin1_symbol ("cancel-thread"));
  1518. join_thread_var =
  1519. scm_module_variable (scm_current_module (),
  1520. scm_from_latin1_symbol ("join-thread"));
  1521. call_with_new_thread_var =
  1522. scm_module_variable (scm_current_module (),
  1523. scm_from_latin1_symbol ("call-with-new-thread"));
  1524. }
  1525. void
  1526. scm_init_threads ()
  1527. {
  1528. scm_tc16_thread = scm_make_smob_type ("thread", sizeof (scm_thread));
  1529. scm_set_smob_print (scm_tc16_thread, thread_print);
  1530. scm_tc16_mutex = scm_make_smob_type ("mutex", sizeof (struct scm_mutex));
  1531. scm_set_smob_print (scm_tc16_mutex, scm_mutex_print);
  1532. scm_tc16_condvar = scm_make_smob_type ("condition-variable",
  1533. sizeof (struct scm_cond));
  1534. scm_set_smob_print (scm_tc16_condvar, scm_cond_print);
  1535. default_dynamic_state = SCM_BOOL_F;
  1536. guilify_self_2 (scm_i_make_initial_dynamic_state ());
  1537. threads_initialized_p = 1;
  1538. scm_c_register_extension ("libguile-" SCM_EFFECTIVE_VERSION,
  1539. "scm_init_ice_9_threads",
  1540. scm_init_ice_9_threads, NULL);
  1541. }
  1542. void
  1543. scm_init_threads_default_dynamic_state ()
  1544. {
  1545. default_dynamic_state = scm_current_dynamic_state ();
  1546. }