threads.c 48 KB

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