threads.c 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844
  1. /* Copyright 1995-1998,2000-2014,2018-2019,2023-2024
  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, in which case we should shut it down also by closing its
  399. read pipe. */
  400. if (thread_count <= 1)
  401. scm_i_close_signal_pipe ();
  402. scm_i_pthread_mutex_unlock (&thread_admin_mutex);
  403. /* Although this thread has exited, the thread object might still be
  404. alive. Release unused memory. */
  405. for (size_t n = 0; n < SCM_INLINE_GC_FREELIST_COUNT; n++)
  406. t->freelists[n] = t->pointerless_freelists[n] = NULL;
  407. t->dynamic_state = NULL;
  408. t->dynstack.base = NULL;
  409. t->dynstack.top = NULL;
  410. t->dynstack.limit = NULL;
  411. scm_i_vm_free_stack (&t->vm);
  412. #if ENABLE_JIT
  413. scm_jit_state_free (t->jit_state);
  414. #endif
  415. t->jit_state = NULL;
  416. #ifdef SCM_HAVE_THREAD_STORAGE_CLASS
  417. scm_i_current_thread = NULL;
  418. #endif
  419. #if SCM_USE_PTHREAD_THREADS
  420. if (t->needs_unregister)
  421. GC_unregister_my_thread ();
  422. #endif
  423. }
  424. static scm_i_pthread_once_t init_thread_key_once = SCM_I_PTHREAD_ONCE_INIT;
  425. static void
  426. init_thread_key (void)
  427. {
  428. scm_i_pthread_key_create (&scm_i_thread_key, on_thread_exit);
  429. }
  430. /* Perform any initializations necessary to make the current thread
  431. known to Guile (via SCM_I_CURRENT_THREAD), initializing Guile itself,
  432. if necessary.
  433. BASE is the stack base to use with GC.
  434. DYNAMIC_STATE is the set of fluid values to start with.
  435. Returns zero when the thread was known to guile already; otherwise
  436. return 1.
  437. Note that it could be the case that the thread was known
  438. to Guile, but not in guile mode (because we are within a
  439. scm_without_guile call). Check SCM_I_CURRENT_THREAD->guile_mode to
  440. be sure. New threads are put into guile mode implicitly. */
  441. static int
  442. scm_i_init_thread_for_guile (struct GC_stack_base *base,
  443. SCM dynamic_state)
  444. {
  445. scm_i_pthread_once (&init_thread_key_once, init_thread_key);
  446. if (SCM_I_CURRENT_THREAD)
  447. {
  448. /* Thread is already known to Guile.
  449. */
  450. return 0;
  451. }
  452. else
  453. {
  454. /* This thread has not been guilified yet.
  455. */
  456. scm_i_pthread_mutex_lock (&scm_i_init_mutex);
  457. if (scm_initialized_p == 0)
  458. {
  459. /* First thread ever to enter Guile. Run the full
  460. initialization.
  461. */
  462. scm_i_init_guile (base);
  463. #if SCM_USE_PTHREAD_THREADS
  464. /* Allow other threads to come in later. */
  465. GC_allow_register_threads ();
  466. #endif
  467. scm_i_pthread_mutex_unlock (&scm_i_init_mutex);
  468. }
  469. else
  470. {
  471. int needs_unregister = 0;
  472. /* Guile is already initialized, but this thread enters it for
  473. the first time. Only initialize this thread.
  474. */
  475. scm_i_pthread_mutex_unlock (&scm_i_init_mutex);
  476. /* Register this thread with libgc. */
  477. #if SCM_USE_PTHREAD_THREADS
  478. if (GC_register_my_thread (base) == GC_SUCCESS)
  479. needs_unregister = 1;
  480. #endif
  481. guilify_self_1 (base, needs_unregister);
  482. guilify_self_2 (dynamic_state);
  483. }
  484. return 1;
  485. }
  486. }
  487. void
  488. scm_init_guile ()
  489. {
  490. struct GC_stack_base stack_base;
  491. if (GC_get_stack_base (&stack_base) == GC_SUCCESS)
  492. scm_i_init_thread_for_guile (&stack_base, default_dynamic_state);
  493. else
  494. {
  495. fprintf (stderr, "Failed to get stack base for current thread.\n");
  496. exit (EXIT_FAILURE);
  497. }
  498. }
  499. struct with_guile_args
  500. {
  501. GC_fn_type func;
  502. void *data;
  503. SCM dynamic_state;
  504. };
  505. static void *
  506. with_guile_trampoline (void *data)
  507. {
  508. struct with_guile_args *args = data;
  509. return scm_c_with_continuation_barrier (args->func, args->data);
  510. }
  511. static void *
  512. with_guile (struct GC_stack_base *base, void *data)
  513. {
  514. void *res;
  515. int new_thread;
  516. scm_thread *t;
  517. struct with_guile_args *args = data;
  518. new_thread = scm_i_init_thread_for_guile (base, args->dynamic_state);
  519. t = SCM_I_CURRENT_THREAD;
  520. if (new_thread)
  521. {
  522. /* We are in Guile mode. */
  523. assert (t->guile_mode);
  524. res = scm_c_with_continuation_barrier (args->func, args->data);
  525. /* Leave Guile mode. */
  526. t->guile_mode = 0;
  527. }
  528. else if (t->guile_mode)
  529. {
  530. /* Already in Guile mode. */
  531. res = scm_c_with_continuation_barrier (args->func, args->data);
  532. }
  533. else
  534. {
  535. /* We are not in Guile mode, either because we are not within a
  536. scm_with_guile, or because we are within a scm_without_guile.
  537. This call to scm_with_guile() could happen from anywhere on the
  538. stack, and in particular lower on the stack than when it was
  539. when this thread was first guilified. Thus, `base' must be
  540. updated. */
  541. #if SCM_STACK_GROWS_UP
  542. if (SCM_STACK_PTR (base->mem_base) < t->base)
  543. t->base = SCM_STACK_PTR (base->mem_base);
  544. #else
  545. if (SCM_STACK_PTR (base->mem_base) > t->base)
  546. t->base = SCM_STACK_PTR (base->mem_base);
  547. #endif
  548. t->guile_mode = 1;
  549. res = GC_call_with_gc_active (with_guile_trampoline, args);
  550. t->guile_mode = 0;
  551. }
  552. return res;
  553. }
  554. static void *
  555. scm_i_with_guile (void *(*func)(void *), void *data, SCM dynamic_state)
  556. {
  557. struct with_guile_args args;
  558. args.func = func;
  559. args.data = data;
  560. args.dynamic_state = dynamic_state;
  561. return GC_call_with_stack_base (with_guile, &args);
  562. }
  563. void *
  564. scm_with_guile (void *(*func)(void *), void *data)
  565. {
  566. return scm_i_with_guile (func, data, default_dynamic_state);
  567. }
  568. void *
  569. scm_without_guile (void *(*func)(void *), void *data)
  570. {
  571. void *result;
  572. scm_thread *t = SCM_I_CURRENT_THREAD;
  573. if (t->guile_mode)
  574. {
  575. SCM_I_CURRENT_THREAD->guile_mode = 0;
  576. result = GC_do_blocking (func, data);
  577. SCM_I_CURRENT_THREAD->guile_mode = 1;
  578. }
  579. else
  580. /* Otherwise we're not in guile mode, so nothing to do. */
  581. result = func (data);
  582. return result;
  583. }
  584. /*** Thread creation */
  585. /* Because (ice-9 boot-9) loads up (ice-9 threads), we know that this
  586. variable will get loaded before a call to scm_call_with_new_thread
  587. and therefore no lock or pthread_once_t is needed. */
  588. static SCM call_with_new_thread_var;
  589. SCM
  590. scm_call_with_new_thread (SCM thunk, SCM handler)
  591. {
  592. SCM call_with_new_thread = scm_variable_ref (call_with_new_thread_var);
  593. if (SCM_UNBNDP (handler))
  594. return scm_call_1 (call_with_new_thread, thunk);
  595. return scm_call_2 (call_with_new_thread, thunk, handler);
  596. }
  597. typedef struct launch_data launch_data;
  598. struct launch_data {
  599. launch_data *prev;
  600. launch_data *next;
  601. SCM dynamic_state;
  602. SCM thunk;
  603. };
  604. /* GC-protect the launch data for new threads. */
  605. static launch_data *protected_launch_data;
  606. static scm_i_pthread_mutex_t protected_launch_data_lock =
  607. SCM_I_PTHREAD_MUTEX_INITIALIZER;
  608. static void
  609. protect_launch_data (launch_data *data)
  610. {
  611. scm_i_pthread_mutex_lock (&protected_launch_data_lock);
  612. data->next = protected_launch_data;
  613. if (protected_launch_data)
  614. protected_launch_data->prev = data;
  615. protected_launch_data = data;
  616. scm_i_pthread_mutex_unlock (&protected_launch_data_lock);
  617. }
  618. static void
  619. unprotect_launch_data (launch_data *data)
  620. {
  621. scm_i_pthread_mutex_lock (&protected_launch_data_lock);
  622. if (data->next)
  623. data->next->prev = data->prev;
  624. if (data->prev)
  625. data->prev->next = data->next;
  626. else
  627. protected_launch_data = data->next;
  628. scm_i_pthread_mutex_unlock (&protected_launch_data_lock);
  629. }
  630. static void *
  631. really_launch (void *d)
  632. {
  633. scm_thread *t = SCM_I_CURRENT_THREAD;
  634. unprotect_launch_data (d);
  635. /* The thread starts with asyncs blocked. */
  636. t->block_asyncs++;
  637. SCM_I_CURRENT_THREAD->result = scm_call_0 (((launch_data *)d)->thunk);
  638. return 0;
  639. }
  640. static void *
  641. launch_thread (void *d)
  642. {
  643. launch_data *data = (launch_data *)d;
  644. scm_i_pthread_detach (scm_i_pthread_self ());
  645. scm_i_with_guile (really_launch, d, data->dynamic_state);
  646. return NULL;
  647. }
  648. SCM_INTERNAL SCM scm_sys_call_with_new_thread (SCM);
  649. SCM_DEFINE (scm_sys_call_with_new_thread, "%call-with-new-thread", 1, 0, 0,
  650. (SCM thunk), "")
  651. #define FUNC_NAME s_scm_sys_call_with_new_thread
  652. {
  653. launch_data *data;
  654. scm_i_pthread_t id;
  655. int err;
  656. SCM_ASSERT (scm_is_true (scm_thunk_p (thunk)), thunk, SCM_ARG1, FUNC_NAME);
  657. GC_collect_a_little ();
  658. data = scm_gc_typed_calloc (launch_data);
  659. data->dynamic_state = scm_current_dynamic_state ();
  660. data->thunk = thunk;
  661. protect_launch_data (data);
  662. err = scm_i_pthread_create (&id, NULL, launch_thread, data);
  663. if (err)
  664. {
  665. errno = err;
  666. scm_syserror (NULL);
  667. }
  668. return SCM_UNSPECIFIED;
  669. }
  670. #undef FUNC_NAME
  671. SCM
  672. scm_spawn_thread (scm_t_catch_body body, void *body_data,
  673. scm_t_catch_handler handler, void *handler_data)
  674. {
  675. SCM body_closure, handler_closure;
  676. body_closure = scm_c_make_thunk (body, body_data);
  677. handler_closure = handler == NULL ? SCM_UNDEFINED :
  678. scm_i_make_catch_handler (handler, handler_data);
  679. return scm_call_with_new_thread (body_closure, handler_closure);
  680. }
  681. SCM_DEFINE (scm_yield, "yield", 0, 0, 0,
  682. (),
  683. "Move the calling thread to the end of the scheduling queue.")
  684. #define FUNC_NAME s_scm_yield
  685. {
  686. return scm_from_bool (scm_i_sched_yield ());
  687. }
  688. #undef FUNC_NAME
  689. static SCM cancel_thread_var;
  690. SCM
  691. scm_cancel_thread (SCM thread)
  692. {
  693. scm_call_1 (scm_variable_ref (cancel_thread_var), thread);
  694. return SCM_UNSPECIFIED;
  695. }
  696. static SCM join_thread_var;
  697. SCM
  698. scm_join_thread (SCM thread)
  699. {
  700. return scm_call_1 (scm_variable_ref (join_thread_var), thread);
  701. }
  702. SCM
  703. scm_join_thread_timed (SCM thread, SCM timeout, SCM timeoutval)
  704. {
  705. SCM join_thread = scm_variable_ref (join_thread_var);
  706. if (SCM_UNBNDP (timeout))
  707. return scm_call_1 (join_thread, thread);
  708. else if (SCM_UNBNDP (timeoutval))
  709. return scm_call_2 (join_thread, thread, timeout);
  710. else
  711. return scm_call_3 (join_thread, thread, timeout, timeoutval);
  712. }
  713. SCM_DEFINE (scm_thread_p, "thread?", 1, 0, 0,
  714. (SCM obj),
  715. "Return @code{#t} if @var{obj} is a thread.")
  716. #define FUNC_NAME s_scm_thread_p
  717. {
  718. return SCM_I_IS_THREAD(obj) ? SCM_BOOL_T : SCM_BOOL_F;
  719. }
  720. #undef FUNC_NAME
  721. /* We implement our own mutex type since we want them to be 'fair', we
  722. want to do fancy things while waiting for them (like running
  723. asyncs) and we might want to add things that are nice for
  724. debugging.
  725. */
  726. enum scm_mutex_kind {
  727. /* A standard mutex can only be locked once. If you try to lock it
  728. again from the thread that locked it to begin with (the "owner"
  729. thread), it throws an error. It can only be unlocked from the
  730. thread that locked it in the first place. */
  731. SCM_MUTEX_STANDARD,
  732. /* A recursive mutex can be locked multiple times by its owner. It
  733. then has to be unlocked the corresponding number of times, and like
  734. standard mutexes can only be unlocked by the owner thread. */
  735. SCM_MUTEX_RECURSIVE,
  736. /* An unowned mutex is like a standard mutex, except that it can be
  737. unlocked by any thread. A corrolary of this behavior is that a
  738. thread's attempt to lock a mutex that it already owns will block
  739. instead of signaling an error, as it could be that some other
  740. thread unlocks the mutex, allowing the owner thread to proceed.
  741. This kind of mutex is a bit strange and is here for use by
  742. SRFI-18. */
  743. SCM_MUTEX_UNOWNED
  744. };
  745. struct scm_mutex {
  746. scm_i_pthread_mutex_t lock;
  747. /* The thread that owns this mutex, or #f if the mutex is unlocked. */
  748. SCM owner;
  749. /* Queue of threads waiting for this mutex. */
  750. SCM waiting;
  751. /* For SCM_MUTEX_RECURSIVE (and only SCM_MUTEX_RECURSIVE), the
  752. recursive lock count. The first lock does not count. */
  753. int level;
  754. };
  755. #define SCM_MUTEXP(x) SCM_SMOB_PREDICATE (scm_tc16_mutex, x)
  756. #define SCM_MUTEX_DATA(x) ((struct scm_mutex *) SCM_SMOB_DATA (x))
  757. #define SCM_MUTEX_KIND(x) ((enum scm_mutex_kind) (SCM_SMOB_FLAGS (x) & 0x3))
  758. static int
  759. scm_mutex_print (SCM mx, SCM port, scm_print_state *pstate SCM_UNUSED)
  760. {
  761. struct scm_mutex *m = SCM_MUTEX_DATA (mx);
  762. scm_puts ("#<mutex ", port);
  763. scm_uintprint ((scm_t_bits)m, 16, port);
  764. scm_puts (">", port);
  765. return 1;
  766. }
  767. SCM_SYMBOL (allow_external_unlock_sym, "allow-external-unlock");
  768. SCM_SYMBOL (recursive_sym, "recursive");
  769. SCM_DEFINE (scm_make_mutex_with_kind, "make-mutex", 0, 1, 0,
  770. (SCM kind),
  771. "Create a new mutex. If @var{kind} is not given, the mutex\n"
  772. "will be a standard non-recursive mutex. Otherwise pass\n"
  773. "@code{recursive} to make a recursive mutex, or\n"
  774. "@code{allow-external-unlock} to make a non-recursive mutex\n"
  775. "that can be unlocked from any thread.")
  776. #define FUNC_NAME s_scm_make_mutex_with_kind
  777. {
  778. enum scm_mutex_kind mkind = SCM_MUTEX_STANDARD;
  779. struct scm_mutex *m;
  780. scm_i_pthread_mutex_t lock = SCM_I_PTHREAD_MUTEX_INITIALIZER;
  781. if (!SCM_UNBNDP (kind))
  782. {
  783. if (scm_is_eq (kind, allow_external_unlock_sym))
  784. mkind = SCM_MUTEX_UNOWNED;
  785. else if (scm_is_eq (kind, recursive_sym))
  786. mkind = SCM_MUTEX_RECURSIVE;
  787. else
  788. SCM_MISC_ERROR ("unsupported mutex kind: ~a", scm_list_1 (kind));
  789. }
  790. m = scm_gc_malloc (sizeof (struct scm_mutex), "mutex");
  791. /* Because PTHREAD_MUTEX_INITIALIZER is static, it's plain old data,
  792. and so we can just copy it. */
  793. memcpy (&m->lock, &lock, sizeof (m->lock));
  794. m->owner = SCM_BOOL_F;
  795. m->level = 0;
  796. m->waiting = make_queue ();
  797. return scm_new_smob (scm_tc16_mutex | (mkind << 16), (scm_t_bits) m);
  798. }
  799. #undef FUNC_NAME
  800. SCM
  801. scm_make_mutex (void)
  802. {
  803. return scm_make_mutex_with_kind (SCM_UNDEFINED);
  804. }
  805. SCM_DEFINE (scm_make_recursive_mutex, "make-recursive-mutex", 0, 0, 0,
  806. (void),
  807. "Create a new recursive mutex. ")
  808. #define FUNC_NAME s_scm_make_recursive_mutex
  809. {
  810. return scm_make_mutex_with_kind (recursive_sym);
  811. }
  812. #undef FUNC_NAME
  813. SCM
  814. scm_lock_mutex (SCM mx)
  815. {
  816. return scm_timed_lock_mutex (mx, SCM_UNDEFINED);
  817. }
  818. static inline SCM
  819. lock_mutex (enum scm_mutex_kind kind, struct scm_mutex *m,
  820. scm_thread *current_thread, scm_t_timespec *waittime)
  821. #define FUNC_NAME "lock-mutex"
  822. {
  823. scm_i_scm_pthread_mutex_lock (&m->lock);
  824. if (scm_is_eq (m->owner, SCM_BOOL_F))
  825. {
  826. m->owner = current_thread->handle;
  827. scm_i_pthread_mutex_unlock (&m->lock);
  828. return SCM_BOOL_T;
  829. }
  830. else if (kind == SCM_MUTEX_RECURSIVE &&
  831. scm_is_eq (m->owner, current_thread->handle))
  832. {
  833. m->level++;
  834. scm_i_pthread_mutex_unlock (&m->lock);
  835. return SCM_BOOL_T;
  836. }
  837. else if (kind == SCM_MUTEX_STANDARD &&
  838. scm_is_eq (m->owner, current_thread->handle))
  839. {
  840. scm_i_pthread_mutex_unlock (&m->lock);
  841. SCM_MISC_ERROR ("mutex already locked by thread", SCM_EOL);
  842. }
  843. else
  844. while (1)
  845. {
  846. int err = block_self (m->waiting, &m->lock, waittime);
  847. if (err == 0)
  848. {
  849. goto maybe_acquire;
  850. }
  851. else if (err == ETIMEDOUT)
  852. {
  853. scm_i_pthread_mutex_unlock (&m->lock);
  854. return SCM_BOOL_F;
  855. }
  856. else if (err == EINTR)
  857. {
  858. scm_i_pthread_mutex_unlock (&m->lock);
  859. scm_async_tick ();
  860. scm_i_scm_pthread_mutex_lock (&m->lock);
  861. goto maybe_acquire;
  862. }
  863. else
  864. {
  865. /* Shouldn't happen. */
  866. scm_i_pthread_mutex_unlock (&m->lock);
  867. errno = err;
  868. SCM_SYSERROR;
  869. }
  870. maybe_acquire:
  871. if (scm_is_eq (m->owner, SCM_BOOL_F))
  872. {
  873. m->owner = current_thread->handle;
  874. scm_i_pthread_mutex_unlock (&m->lock);
  875. return SCM_BOOL_T;
  876. }
  877. }
  878. }
  879. #undef FUNC_NAME
  880. SCM_DEFINE (scm_timed_lock_mutex, "lock-mutex", 1, 1, 0,
  881. (SCM mutex, SCM timeout),
  882. "Lock mutex @var{mutex}. If the mutex is already locked, "
  883. "the calling thread blocks until the mutex becomes available.")
  884. #define FUNC_NAME s_scm_timed_lock_mutex
  885. {
  886. scm_t_timespec cwaittime, *waittime = NULL;
  887. struct scm_mutex *m;
  888. scm_thread *t = SCM_I_CURRENT_THREAD;
  889. SCM ret;
  890. SCM_VALIDATE_MUTEX (1, mutex);
  891. m = SCM_MUTEX_DATA (mutex);
  892. if (! SCM_UNBNDP (timeout) && ! scm_is_false (timeout))
  893. {
  894. to_timespec (timeout, &cwaittime);
  895. waittime = &cwaittime;
  896. }
  897. /* Specialized lock_mutex implementations according to the mutex
  898. kind. */
  899. switch (SCM_MUTEX_KIND (mutex))
  900. {
  901. case SCM_MUTEX_STANDARD:
  902. ret = lock_mutex (SCM_MUTEX_STANDARD, m, t, waittime);
  903. break;
  904. case SCM_MUTEX_RECURSIVE:
  905. ret = lock_mutex (SCM_MUTEX_RECURSIVE, m, t, waittime);
  906. break;
  907. case SCM_MUTEX_UNOWNED:
  908. ret = lock_mutex (SCM_MUTEX_UNOWNED, m, t, waittime);
  909. break;
  910. default:
  911. abort ();
  912. }
  913. scm_remember_upto_here_1 (mutex);
  914. return ret;
  915. }
  916. #undef FUNC_NAME
  917. static void
  918. lock_mutex_return_void (SCM mx)
  919. {
  920. (void) scm_lock_mutex (mx);
  921. }
  922. static void
  923. unlock_mutex_return_void (SCM mx)
  924. {
  925. (void) scm_unlock_mutex (mx);
  926. }
  927. void
  928. scm_dynwind_lock_mutex (SCM mutex)
  929. {
  930. scm_dynwind_unwind_handler_with_scm (unlock_mutex_return_void, mutex,
  931. SCM_F_WIND_EXPLICITLY);
  932. scm_dynwind_rewind_handler_with_scm (lock_mutex_return_void, mutex,
  933. SCM_F_WIND_EXPLICITLY);
  934. }
  935. SCM
  936. scm_try_mutex (SCM mutex)
  937. {
  938. return scm_timed_lock_mutex (mutex, SCM_INUM0);
  939. }
  940. /* This function is static inline so that the compiler can specialize it
  941. against the mutex kind. */
  942. static inline void
  943. unlock_mutex (enum scm_mutex_kind kind, struct scm_mutex *m,
  944. scm_thread *current_thread)
  945. #define FUNC_NAME "unlock-mutex"
  946. {
  947. scm_i_scm_pthread_mutex_lock (&m->lock);
  948. if (!scm_is_eq (m->owner, current_thread->handle))
  949. {
  950. if (scm_is_eq (m->owner, SCM_BOOL_F))
  951. {
  952. scm_i_pthread_mutex_unlock (&m->lock);
  953. SCM_MISC_ERROR ("mutex not locked", SCM_EOL);
  954. }
  955. if (kind != SCM_MUTEX_UNOWNED)
  956. {
  957. scm_i_pthread_mutex_unlock (&m->lock);
  958. SCM_MISC_ERROR ("mutex not locked by current thread", SCM_EOL);
  959. }
  960. }
  961. if (kind == SCM_MUTEX_RECURSIVE && m->level > 0)
  962. m->level--;
  963. else
  964. {
  965. m->owner = SCM_BOOL_F;
  966. /* Wake up one waiter. */
  967. unblock_from_queue (m->waiting);
  968. }
  969. scm_i_pthread_mutex_unlock (&m->lock);
  970. }
  971. #undef FUNC_NAME
  972. SCM_DEFINE (scm_unlock_mutex, "unlock-mutex", 1, 0, 0, (SCM mutex),
  973. "Unlocks @var{mutex}. The calling thread must already hold\n"
  974. "the lock on @var{mutex}, unless the mutex was created with\n"
  975. "the @code{allow-external-unlock} option; otherwise an error\n"
  976. "will be signaled.")
  977. #define FUNC_NAME s_scm_unlock_mutex
  978. {
  979. struct scm_mutex *m;
  980. scm_thread *t = SCM_I_CURRENT_THREAD;
  981. SCM_VALIDATE_MUTEX (1, mutex);
  982. m = SCM_MUTEX_DATA (mutex);
  983. /* Specialized unlock_mutex implementations according to the mutex
  984. kind. */
  985. switch (SCM_MUTEX_KIND (mutex))
  986. {
  987. case SCM_MUTEX_STANDARD:
  988. unlock_mutex (SCM_MUTEX_STANDARD, m, t);
  989. break;
  990. case SCM_MUTEX_RECURSIVE:
  991. unlock_mutex (SCM_MUTEX_RECURSIVE, m, t);
  992. break;
  993. case SCM_MUTEX_UNOWNED:
  994. unlock_mutex (SCM_MUTEX_UNOWNED, m, t);
  995. break;
  996. default:
  997. abort ();
  998. }
  999. scm_remember_upto_here_1 (mutex);
  1000. return SCM_BOOL_T;
  1001. }
  1002. #undef FUNC_NAME
  1003. SCM_DEFINE (scm_mutex_p, "mutex?", 1, 0, 0,
  1004. (SCM obj),
  1005. "Return @code{#t} if @var{obj} is a mutex.")
  1006. #define FUNC_NAME s_scm_mutex_p
  1007. {
  1008. return SCM_MUTEXP (obj) ? SCM_BOOL_T : SCM_BOOL_F;
  1009. }
  1010. #undef FUNC_NAME
  1011. SCM_DEFINE (scm_mutex_owner, "mutex-owner", 1, 0, 0,
  1012. (SCM mx),
  1013. "Return the thread owning @var{mx}, or @code{#f}.")
  1014. #define FUNC_NAME s_scm_mutex_owner
  1015. {
  1016. SCM owner;
  1017. struct scm_mutex *m = NULL;
  1018. SCM_VALIDATE_MUTEX (1, mx);
  1019. m = SCM_MUTEX_DATA (mx);
  1020. scm_i_pthread_mutex_lock (&m->lock);
  1021. owner = m->owner;
  1022. scm_i_pthread_mutex_unlock (&m->lock);
  1023. return owner;
  1024. }
  1025. #undef FUNC_NAME
  1026. SCM_DEFINE (scm_mutex_level, "mutex-level", 1, 0, 0,
  1027. (SCM mx),
  1028. "Return the lock level of mutex @var{mx}.")
  1029. #define FUNC_NAME s_scm_mutex_level
  1030. {
  1031. SCM_VALIDATE_MUTEX (1, mx);
  1032. if (SCM_MUTEX_KIND (mx) == SCM_MUTEX_RECURSIVE)
  1033. return scm_from_int (SCM_MUTEX_DATA (mx)->level + 1);
  1034. else if (scm_is_eq (SCM_MUTEX_DATA (mx)->owner, SCM_BOOL_F))
  1035. return SCM_INUM0;
  1036. else
  1037. return SCM_INUM1;
  1038. }
  1039. #undef FUNC_NAME
  1040. SCM_DEFINE (scm_mutex_locked_p, "mutex-locked?", 1, 0, 0,
  1041. (SCM mx),
  1042. "Returns @code{#t} if the mutex @var{mx} is locked.")
  1043. #define FUNC_NAME s_scm_mutex_locked_p
  1044. {
  1045. SCM_VALIDATE_MUTEX (1, mx);
  1046. if (scm_is_eq (SCM_MUTEX_DATA (mx)->owner, SCM_BOOL_F))
  1047. return SCM_BOOL_F;
  1048. else
  1049. return SCM_BOOL_T;
  1050. }
  1051. #undef FUNC_NAME
  1052. struct scm_cond {
  1053. scm_i_pthread_mutex_t lock;
  1054. SCM waiting; /* the threads waiting for this condition. */
  1055. };
  1056. #define SCM_CONDVARP(x) SCM_SMOB_PREDICATE (scm_tc16_condvar, x)
  1057. #define SCM_CONDVAR_DATA(x) ((struct scm_cond *) SCM_SMOB_DATA (x))
  1058. static int
  1059. scm_cond_print (SCM cv, SCM port, scm_print_state *pstate SCM_UNUSED)
  1060. {
  1061. struct scm_cond *c = SCM_CONDVAR_DATA (cv);
  1062. scm_puts ("#<condition-variable ", port);
  1063. scm_uintprint ((scm_t_bits)c, 16, port);
  1064. scm_puts (">", port);
  1065. return 1;
  1066. }
  1067. SCM_DEFINE (scm_make_condition_variable, "make-condition-variable", 0, 0, 0,
  1068. (void),
  1069. "Make a new condition variable.")
  1070. #define FUNC_NAME s_scm_make_condition_variable
  1071. {
  1072. struct scm_cond *c;
  1073. SCM cv;
  1074. c = scm_gc_malloc (sizeof (struct scm_cond), "condition variable");
  1075. c->waiting = SCM_EOL;
  1076. SCM_NEWSMOB (cv, scm_tc16_condvar, (scm_t_bits) c);
  1077. c->waiting = make_queue ();
  1078. return cv;
  1079. }
  1080. #undef FUNC_NAME
  1081. static inline SCM
  1082. timed_wait (enum scm_mutex_kind kind, struct scm_mutex *m, struct scm_cond *c,
  1083. scm_thread *current_thread, scm_t_timespec *waittime)
  1084. #define FUNC_NAME "wait-condition-variable"
  1085. {
  1086. scm_i_scm_pthread_mutex_lock (&m->lock);
  1087. if (!scm_is_eq (m->owner, current_thread->handle))
  1088. {
  1089. if (scm_is_eq (m->owner, SCM_BOOL_F))
  1090. {
  1091. scm_i_pthread_mutex_unlock (&m->lock);
  1092. SCM_MISC_ERROR ("mutex not locked", SCM_EOL);
  1093. }
  1094. if (kind != SCM_MUTEX_UNOWNED)
  1095. {
  1096. scm_i_pthread_mutex_unlock (&m->lock);
  1097. SCM_MISC_ERROR ("mutex not locked by current thread", SCM_EOL);
  1098. }
  1099. }
  1100. while (1)
  1101. {
  1102. int err = 0;
  1103. /* Unlock the mutex. */
  1104. if (kind == SCM_MUTEX_RECURSIVE && m->level > 0)
  1105. m->level--;
  1106. else
  1107. {
  1108. m->owner = SCM_BOOL_F;
  1109. /* Wake up one waiter. */
  1110. unblock_from_queue (m->waiting);
  1111. }
  1112. /* Wait for someone to signal the cond, a timeout, or an
  1113. interrupt. */
  1114. err = block_self (c->waiting, &m->lock, waittime);
  1115. /* We woke up for some reason. Reacquire the mutex before doing
  1116. anything else.
  1117. FIXME: We disable interrupts while reacquiring the mutex. If
  1118. we allow interrupts here, there's the risk of a nonlocal exit
  1119. before we reaquire the mutex, which would be visible to user
  1120. code.
  1121. For example the unwind handler in
  1122. (with-mutex m (wait-condition-variable c m))
  1123. that tries to unlock M could see M in an already-unlocked
  1124. state, if an interrupt while waiting on C caused the wait to
  1125. abort and the woke thread lost the race to reacquire M. That's
  1126. not great. Maybe it's necessary but for now we just disable
  1127. interrupts while reaquiring a mutex after a wait. */
  1128. current_thread->block_asyncs++;
  1129. if (kind == SCM_MUTEX_RECURSIVE &&
  1130. scm_is_eq (m->owner, current_thread->handle))
  1131. {
  1132. m->level++;
  1133. scm_i_pthread_mutex_unlock (&m->lock);
  1134. }
  1135. else
  1136. while (1)
  1137. {
  1138. if (scm_is_eq (m->owner, SCM_BOOL_F))
  1139. {
  1140. m->owner = current_thread->handle;
  1141. scm_i_pthread_mutex_unlock (&m->lock);
  1142. break;
  1143. }
  1144. block_self (m->waiting, &m->lock, waittime);
  1145. }
  1146. current_thread->block_asyncs--;
  1147. /* Now that we have the mutex again, handle the return value. */
  1148. if (err == 0)
  1149. return SCM_BOOL_T;
  1150. else if (err == ETIMEDOUT)
  1151. return SCM_BOOL_F;
  1152. else if (err == EINTR)
  1153. /* Let caller run scm_async_tick() and loop. */
  1154. return SCM_BOOL_T;
  1155. else
  1156. {
  1157. /* Shouldn't happen. */
  1158. errno = err;
  1159. SCM_SYSERROR;
  1160. }
  1161. }
  1162. }
  1163. #undef FUNC_NAME
  1164. SCM_DEFINE (scm_timed_wait_condition_variable, "wait-condition-variable", 2, 1, 0,
  1165. (SCM cond, SCM mutex, SCM timeout),
  1166. "Wait until condition variable @var{cv} has been signaled. While waiting, "
  1167. "mutex @var{mx} is atomically unlocked (as with @code{unlock-mutex}) and "
  1168. "is locked again when this function returns. When @var{t} is given, "
  1169. "it specifies a point in time where the waiting should be aborted. It "
  1170. "can be either a integer as returned by @code{current-time} or a pair "
  1171. "as returned by @code{gettimeofday}. When the waiting is aborted the "
  1172. "mutex is locked and @code{#f} is returned. After the condition "
  1173. "variable is signaled, the mutex is locked and @code{#t} is returned. "
  1174. "@code{#t} may also be returned spuriously, so any relevant conditions "
  1175. "should be re-checked.")
  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. scm_thread *t;
  1413. scm_i_pthread_mutex_lock (&thread_admin_mutex);
  1414. int n = thread_count;
  1415. SCM list = scm_c_make_list (n, SCM_UNSPECIFIED);
  1416. SCM *l = &list;
  1417. for (t = all_threads; t && n > 0; t = t->next_thread)
  1418. {
  1419. if (!t->exited && !scm_i_is_signal_delivery_thread (t))
  1420. {
  1421. SCM_SETCAR (*l, t->handle);
  1422. l = SCM_CDRLOC (*l);
  1423. }
  1424. n--;
  1425. }
  1426. *l = SCM_EOL;
  1427. scm_i_pthread_mutex_unlock (&thread_admin_mutex);
  1428. return list;
  1429. }
  1430. #undef FUNC_NAME
  1431. SCM_DEFINE (scm_thread_exited_p, "thread-exited?", 1, 0, 0,
  1432. (SCM thread),
  1433. "Return @code{#t} iff @var{thread} has exited.\n")
  1434. #define FUNC_NAME s_scm_thread_exited_p
  1435. {
  1436. return scm_from_bool (scm_c_thread_exited_p (thread));
  1437. }
  1438. #undef FUNC_NAME
  1439. int
  1440. scm_c_thread_exited_p (SCM thread)
  1441. #define FUNC_NAME s_scm_thread_exited_p
  1442. {
  1443. scm_thread *t;
  1444. SCM_VALIDATE_THREAD (1, thread);
  1445. t = SCM_I_THREAD_DATA (thread);
  1446. return t->exited;
  1447. }
  1448. #undef FUNC_NAME
  1449. SCM_DEFINE (scm_total_processor_count, "total-processor-count", 0, 0, 0,
  1450. (void),
  1451. "Return the total number of processors of the machine, which\n"
  1452. "is guaranteed to be at least 1. A ``processor'' here is a\n"
  1453. "thread execution unit, which can be either:\n\n"
  1454. "@itemize\n"
  1455. "@item an execution core in a (possibly multi-core) chip, in a\n"
  1456. " (possibly multi- chip) module, in a single computer, or\n"
  1457. "@item a thread execution unit inside a core in the case of\n"
  1458. " @dfn{hyper-threaded} CPUs.\n"
  1459. "@end itemize\n\n"
  1460. "Which of the two definitions is used, is unspecified.\n")
  1461. #define FUNC_NAME s_scm_total_processor_count
  1462. {
  1463. return scm_from_ulong (num_processors (NPROC_ALL));
  1464. }
  1465. #undef FUNC_NAME
  1466. SCM_DEFINE (scm_current_processor_count, "current-processor-count", 0, 0, 0,
  1467. (void),
  1468. "Like @code{total-processor-count}, but return the number of\n"
  1469. "processors available to the current process. See\n"
  1470. "@code{setaffinity} and @code{getaffinity} for more\n"
  1471. "information.\n")
  1472. #define FUNC_NAME s_scm_current_processor_count
  1473. {
  1474. return scm_from_ulong (num_processors (NPROC_CURRENT));
  1475. }
  1476. #undef FUNC_NAME
  1477. static scm_i_pthread_cond_t wake_up_cond;
  1478. static int threads_initialized_p = 0;
  1479. /*** Initialization */
  1480. scm_i_pthread_mutex_t scm_i_misc_mutex;
  1481. #if SCM_USE_PTHREAD_THREADS
  1482. pthread_mutexattr_t scm_i_pthread_mutexattr_recursive[1];
  1483. #endif
  1484. void
  1485. scm_threads_prehistory (void *base)
  1486. {
  1487. #if SCM_USE_PTHREAD_THREADS
  1488. pthread_mutexattr_init (scm_i_pthread_mutexattr_recursive);
  1489. pthread_mutexattr_settype (scm_i_pthread_mutexattr_recursive,
  1490. PTHREAD_MUTEX_RECURSIVE);
  1491. #endif
  1492. scm_i_pthread_mutex_init (&scm_i_misc_mutex, NULL);
  1493. scm_i_pthread_cond_init (&wake_up_cond, NULL);
  1494. thread_gc_kind =
  1495. GC_new_kind (GC_new_free_list (),
  1496. GC_MAKE_PROC (GC_new_proc (thread_mark), 0),
  1497. 0, 1);
  1498. guilify_self_1 ((struct GC_stack_base *) base, 0);
  1499. }
  1500. scm_t_bits scm_tc16_thread;
  1501. scm_t_bits scm_tc16_mutex;
  1502. scm_t_bits scm_tc16_condvar;
  1503. static void
  1504. scm_init_ice_9_threads (void *unused)
  1505. {
  1506. #include "threads.x"
  1507. cancel_thread_var =
  1508. scm_module_variable (scm_current_module (),
  1509. scm_from_latin1_symbol ("cancel-thread"));
  1510. join_thread_var =
  1511. scm_module_variable (scm_current_module (),
  1512. scm_from_latin1_symbol ("join-thread"));
  1513. call_with_new_thread_var =
  1514. scm_module_variable (scm_current_module (),
  1515. scm_from_latin1_symbol ("call-with-new-thread"));
  1516. }
  1517. void
  1518. scm_init_threads ()
  1519. {
  1520. scm_tc16_thread = scm_make_smob_type ("thread", sizeof (scm_thread));
  1521. scm_set_smob_print (scm_tc16_thread, thread_print);
  1522. scm_tc16_mutex = scm_make_smob_type ("mutex", sizeof (struct scm_mutex));
  1523. scm_set_smob_print (scm_tc16_mutex, scm_mutex_print);
  1524. scm_tc16_condvar = scm_make_smob_type ("condition-variable",
  1525. sizeof (struct scm_cond));
  1526. scm_set_smob_print (scm_tc16_condvar, scm_cond_print);
  1527. default_dynamic_state = SCM_BOOL_F;
  1528. guilify_self_2 (scm_i_make_initial_dynamic_state ());
  1529. threads_initialized_p = 1;
  1530. scm_c_register_extension ("libguile-" SCM_EFFECTIVE_VERSION,
  1531. "scm_init_ice_9_threads",
  1532. scm_init_ice_9_threads, NULL);
  1533. }
  1534. void
  1535. scm_init_threads_default_dynamic_state ()
  1536. {
  1537. default_dynamic_state = scm_current_dynamic_state ();
  1538. }