threads.c 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192
  1. /* Copyright (C) 1995, 1996, 1997, 1998, 2000, 2001, 2002, 2003, 2004,
  2. * 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013,
  3. * 2014 Free Software Foundation, Inc.
  4. *
  5. * This library is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU Lesser General Public License
  7. * as published by the Free Software Foundation; either version 3 of
  8. * the License, or (at your option) any later version.
  9. *
  10. * This library is distributed in the hope that it will be useful, but
  11. * WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. * Lesser General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Lesser General Public
  16. * License along with this library; if not, write to the Free Software
  17. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  18. * 02110-1301 USA
  19. */
  20. #ifdef HAVE_CONFIG_H
  21. # include <config.h>
  22. #endif
  23. #include "libguile/bdw-gc.h"
  24. #include <gc/gc_mark.h>
  25. #include "libguile/_scm.h"
  26. #include <stdlib.h>
  27. #include <unistd.h>
  28. #include <stdio.h>
  29. #ifdef HAVE_STRING_H
  30. #include <string.h> /* for memset used by FD_ZERO on Solaris 10 */
  31. #endif
  32. #if HAVE_SYS_TIME_H
  33. #include <sys/time.h>
  34. #endif
  35. #if HAVE_PTHREAD_NP_H
  36. # include <pthread_np.h>
  37. #endif
  38. #include <sys/select.h>
  39. #include <assert.h>
  40. #include <fcntl.h>
  41. #include <nproc.h>
  42. #include "libguile/validate.h"
  43. #include "libguile/root.h"
  44. #include "libguile/eval.h"
  45. #include "libguile/async.h"
  46. #include "libguile/ports.h"
  47. #include "libguile/threads.h"
  48. #include "libguile/dynwind.h"
  49. #include "libguile/iselect.h"
  50. #include "libguile/fluids.h"
  51. #include "libguile/continuations.h"
  52. #include "libguile/gc.h"
  53. #include "libguile/gc-inline.h"
  54. #include "libguile/init.h"
  55. #include "libguile/scmsigs.h"
  56. #include "libguile/strings.h"
  57. #include "libguile/vm.h"
  58. #include <full-read.h>
  59. /* The GC "kind" for threads that allow them to mark their VM
  60. stacks. */
  61. static int thread_gc_kind;
  62. static struct GC_ms_entry *
  63. thread_mark (GC_word *addr, struct GC_ms_entry *mark_stack_ptr,
  64. struct GC_ms_entry *mark_stack_limit, GC_word env)
  65. {
  66. int word;
  67. const struct scm_i_thread *t = (struct scm_i_thread *) addr;
  68. if (SCM_UNPACK (t->handle) == 0)
  69. /* T must be on the free-list; ignore. (See warning in
  70. gc_mark.h.) */
  71. return mark_stack_ptr;
  72. /* Mark T. We could be more precise, but it doesn't matter. */
  73. for (word = 0; word * sizeof (*addr) < sizeof (*t); word++)
  74. mark_stack_ptr = GC_MARK_AND_PUSH ((void *) addr[word],
  75. mark_stack_ptr, mark_stack_limit,
  76. NULL);
  77. /* The pointerless freelists are threaded through their first word,
  78. but GC doesn't know to trace them (as they are pointerless), so we
  79. need to do that here. See the comments at the top of libgc's
  80. gc_inline.h. */
  81. if (t->pointerless_freelists)
  82. {
  83. size_t n;
  84. for (n = 0; n < SCM_INLINE_GC_FREELIST_COUNT; n++)
  85. {
  86. void *chain = t->pointerless_freelists[n];
  87. if (chain)
  88. {
  89. /* The first link is already marked by the freelist vector,
  90. so we just have to mark the tail. */
  91. while ((chain = *(void **)chain))
  92. mark_stack_ptr = GC_mark_and_push (chain, mark_stack_ptr,
  93. mark_stack_limit, NULL);
  94. }
  95. }
  96. }
  97. if (t->vp)
  98. mark_stack_ptr = scm_i_vm_mark_stack (t->vp, mark_stack_ptr,
  99. mark_stack_limit);
  100. return mark_stack_ptr;
  101. }
  102. static void
  103. to_timespec (SCM t, scm_t_timespec *waittime)
  104. {
  105. if (scm_is_pair (t))
  106. {
  107. waittime->tv_sec = scm_to_ulong (SCM_CAR (t));
  108. waittime->tv_nsec = scm_to_ulong (SCM_CDR (t)) * 1000;
  109. }
  110. else
  111. {
  112. double time = scm_to_double (t);
  113. double sec = scm_c_truncate (time);
  114. waittime->tv_sec = (long) sec;
  115. waittime->tv_nsec = (long) ((time - sec) * 1000000000);
  116. }
  117. }
  118. /*** Queues */
  119. /* Note: We annotate with "GC-robust" assignments whose purpose is to avoid
  120. the risk of false references leading to unbounded retained space as
  121. described in "Bounding Space Usage of Conservative Garbage Collectors",
  122. H.J. Boehm, 2001. */
  123. /* Make an empty queue data structure.
  124. */
  125. static SCM
  126. make_queue ()
  127. {
  128. return scm_cons (SCM_EOL, SCM_EOL);
  129. }
  130. /* Put T at the back of Q and return a handle that can be used with
  131. remqueue to remove T from Q again.
  132. */
  133. static SCM
  134. enqueue (SCM q, SCM t)
  135. {
  136. SCM c = scm_cons (t, SCM_EOL);
  137. SCM_CRITICAL_SECTION_START;
  138. if (scm_is_null (SCM_CDR (q)))
  139. SCM_SETCDR (q, c);
  140. else
  141. SCM_SETCDR (SCM_CAR (q), c);
  142. SCM_SETCAR (q, c);
  143. SCM_CRITICAL_SECTION_END;
  144. return c;
  145. }
  146. /* Remove the element that the handle C refers to from the queue Q. C
  147. must have been returned from a call to enqueue. The return value
  148. is zero when the element referred to by C has already been removed.
  149. Otherwise, 1 is returned.
  150. */
  151. static int
  152. remqueue (SCM q, SCM c)
  153. {
  154. SCM p, prev = q;
  155. SCM_CRITICAL_SECTION_START;
  156. for (p = SCM_CDR (q); !scm_is_null (p); p = SCM_CDR (p))
  157. {
  158. if (scm_is_eq (p, c))
  159. {
  160. if (scm_is_eq (c, SCM_CAR (q)))
  161. SCM_SETCAR (q, scm_is_eq (prev, q) ? SCM_EOL : prev);
  162. SCM_SETCDR (prev, SCM_CDR (c));
  163. /* GC-robust */
  164. SCM_SETCDR (c, SCM_EOL);
  165. SCM_CRITICAL_SECTION_END;
  166. return 1;
  167. }
  168. prev = p;
  169. }
  170. SCM_CRITICAL_SECTION_END;
  171. return 0;
  172. }
  173. /* Remove the front-most element from the queue Q and return it.
  174. Return SCM_BOOL_F when Q is empty.
  175. */
  176. static SCM
  177. dequeue (SCM q)
  178. {
  179. SCM c;
  180. SCM_CRITICAL_SECTION_START;
  181. c = SCM_CDR (q);
  182. if (scm_is_null (c))
  183. {
  184. SCM_CRITICAL_SECTION_END;
  185. return SCM_BOOL_F;
  186. }
  187. else
  188. {
  189. SCM_SETCDR (q, SCM_CDR (c));
  190. if (scm_is_null (SCM_CDR (q)))
  191. SCM_SETCAR (q, SCM_EOL);
  192. SCM_CRITICAL_SECTION_END;
  193. /* GC-robust */
  194. SCM_SETCDR (c, SCM_EOL);
  195. return SCM_CAR (c);
  196. }
  197. }
  198. /*** Thread smob routines */
  199. static int
  200. thread_print (SCM exp, SCM port, scm_print_state *pstate SCM_UNUSED)
  201. {
  202. /* On a Gnu system pthread_t is an unsigned long, but on mingw it's a
  203. struct. A cast like "(unsigned long) t->pthread" is a syntax error in
  204. the struct case, hence we go via a union, and extract according to the
  205. size of pthread_t. */
  206. union {
  207. scm_i_pthread_t p;
  208. unsigned short us;
  209. unsigned int ui;
  210. unsigned long ul;
  211. scm_t_uintmax um;
  212. } u;
  213. scm_i_thread *t = SCM_I_THREAD_DATA (exp);
  214. scm_i_pthread_t p = t->pthread;
  215. scm_t_uintmax id;
  216. u.p = p;
  217. if (sizeof (p) == sizeof (unsigned short))
  218. id = u.us;
  219. else if (sizeof (p) == sizeof (unsigned int))
  220. id = u.ui;
  221. else if (sizeof (p) == sizeof (unsigned long))
  222. id = u.ul;
  223. else
  224. id = u.um;
  225. scm_puts_unlocked ("#<thread ", port);
  226. scm_uintprint (id, 10, port);
  227. scm_puts_unlocked (" (", port);
  228. scm_uintprint ((scm_t_bits)t, 16, port);
  229. scm_puts_unlocked (")>", port);
  230. return 1;
  231. }
  232. /*** Blocking on queues. */
  233. /* See also scm_i_queue_async_cell for how such a block is
  234. interrputed.
  235. */
  236. /* Put the current thread on QUEUE and go to sleep, waiting for it to
  237. be woken up by a call to 'unblock_from_queue', or to be
  238. interrupted. Upon return of this function, the current thread is
  239. no longer on QUEUE, even when the sleep has been interrupted.
  240. The caller of block_self must hold MUTEX. It will be atomically
  241. unlocked while sleeping, just as with scm_i_pthread_cond_wait.
  242. SLEEP_OBJECT is an arbitrary SCM value that is kept alive as long
  243. as MUTEX is needed.
  244. When WAITTIME is not NULL, the sleep will be aborted at that time.
  245. The return value of block_self is an errno value. It will be zero
  246. when the sleep has been successfully completed by a call to
  247. unblock_from_queue, EINTR when it has been interrupted by the
  248. delivery of a system async, and ETIMEDOUT when the timeout has
  249. expired.
  250. The system asyncs themselves are not executed by block_self.
  251. */
  252. static int
  253. block_self (SCM queue, SCM sleep_object, scm_i_pthread_mutex_t *mutex,
  254. const scm_t_timespec *waittime)
  255. {
  256. scm_i_thread *t = SCM_I_CURRENT_THREAD;
  257. SCM q_handle;
  258. int err;
  259. if (scm_i_setup_sleep (t, sleep_object, mutex, -1))
  260. err = EINTR;
  261. else
  262. {
  263. t->block_asyncs++;
  264. q_handle = enqueue (queue, t->handle);
  265. if (waittime == NULL)
  266. err = scm_i_scm_pthread_cond_wait (&t->sleep_cond, mutex);
  267. else
  268. err = scm_i_scm_pthread_cond_timedwait (&t->sleep_cond, mutex, waittime);
  269. /* When we are still on QUEUE, we have been interrupted. We
  270. report this only when no other error (such as a timeout) has
  271. happened above.
  272. */
  273. if (remqueue (queue, q_handle) && err == 0)
  274. err = EINTR;
  275. t->block_asyncs--;
  276. scm_i_reset_sleep (t);
  277. }
  278. return err;
  279. }
  280. /* Wake up the first thread on QUEUE, if any. The awoken thread is
  281. returned, or #f if the queue was empty.
  282. */
  283. static SCM
  284. unblock_from_queue (SCM queue)
  285. {
  286. SCM thread = dequeue (queue);
  287. if (scm_is_true (thread))
  288. scm_i_pthread_cond_signal (&SCM_I_THREAD_DATA(thread)->sleep_cond);
  289. return thread;
  290. }
  291. /* Getting into and out of guile mode.
  292. */
  293. /* Key used to attach a cleanup handler to a given thread. Also, if
  294. thread-local storage is unavailable, this key is used to retrieve the
  295. current thread with `pthread_getspecific ()'. */
  296. scm_i_pthread_key_t scm_i_thread_key;
  297. #ifdef SCM_HAVE_THREAD_STORAGE_CLASS
  298. /* When thread-local storage (TLS) is available, a pointer to the
  299. current-thread object is kept in TLS. Note that storing the thread-object
  300. itself in TLS (rather than a pointer to some malloc'd memory) is not
  301. possible since thread objects may live longer than the actual thread they
  302. represent. */
  303. SCM_THREAD_LOCAL scm_i_thread *scm_i_current_thread = NULL;
  304. #endif /* SCM_HAVE_THREAD_STORAGE_CLASS */
  305. static scm_i_pthread_mutex_t thread_admin_mutex = SCM_I_PTHREAD_MUTEX_INITIALIZER;
  306. static scm_i_thread *all_threads = NULL;
  307. static int thread_count;
  308. static SCM scm_i_default_dynamic_state;
  309. /* Run when a fluid is collected. */
  310. void
  311. scm_i_reset_fluid (size_t n)
  312. {
  313. scm_i_thread *t;
  314. scm_i_pthread_mutex_lock (&thread_admin_mutex);
  315. for (t = all_threads; t; t = t->next_thread)
  316. if (SCM_I_DYNAMIC_STATE_P (t->dynamic_state))
  317. {
  318. SCM v = SCM_I_DYNAMIC_STATE_FLUIDS (t->dynamic_state);
  319. if (n < SCM_SIMPLE_VECTOR_LENGTH (v))
  320. SCM_SIMPLE_VECTOR_SET (v, n, SCM_UNDEFINED);
  321. }
  322. scm_i_pthread_mutex_unlock (&thread_admin_mutex);
  323. }
  324. /* Perform first stage of thread initialisation, in non-guile mode.
  325. */
  326. static void
  327. guilify_self_1 (struct GC_stack_base *base)
  328. {
  329. scm_i_thread t;
  330. /* We must arrange for SCM_I_CURRENT_THREAD to point to a valid value
  331. before allocating anything in this thread, because allocation could
  332. cause GC to run, and GC could cause finalizers, which could invoke
  333. Scheme functions, which need the current thread to be set. */
  334. t.pthread = scm_i_pthread_self ();
  335. t.handle = SCM_BOOL_F;
  336. t.result = SCM_BOOL_F;
  337. t.cleanup_handler = SCM_BOOL_F;
  338. t.mutexes = SCM_EOL;
  339. t.held_mutex = NULL;
  340. t.join_queue = SCM_EOL;
  341. t.freelists = NULL;
  342. t.pointerless_freelists = NULL;
  343. t.dynamic_state = SCM_BOOL_F;
  344. t.dynstack.base = NULL;
  345. t.dynstack.top = NULL;
  346. t.dynstack.limit = NULL;
  347. t.active_asyncs = SCM_EOL;
  348. t.block_asyncs = 1;
  349. t.pending_asyncs = 1;
  350. t.critical_section_level = 0;
  351. t.base = base->mem_base;
  352. #ifdef __ia64__
  353. t.register_backing_store_base = base->reg_base;
  354. #endif
  355. t.continuation_root = SCM_EOL;
  356. t.continuation_base = t.base;
  357. scm_i_pthread_cond_init (&t.sleep_cond, NULL);
  358. t.sleep_mutex = NULL;
  359. t.sleep_object = SCM_BOOL_F;
  360. t.sleep_fd = -1;
  361. t.vp = NULL;
  362. if (pipe2 (t.sleep_pipe, O_CLOEXEC) != 0)
  363. /* FIXME: Error conditions during the initialization phase are handled
  364. gracelessly since public functions such as `scm_init_guile ()'
  365. currently have type `void'. */
  366. abort ();
  367. scm_i_pthread_mutex_init (&t.admin_mutex, NULL);
  368. t.canceled = 0;
  369. t.exited = 0;
  370. t.guile_mode = 0;
  371. /* The switcheroo. */
  372. {
  373. scm_i_thread *t_ptr = &t;
  374. GC_disable ();
  375. t_ptr = GC_generic_malloc (sizeof (*t_ptr), thread_gc_kind);
  376. memcpy (t_ptr, &t, sizeof t);
  377. scm_i_pthread_setspecific (scm_i_thread_key, t_ptr);
  378. #ifdef SCM_HAVE_THREAD_STORAGE_CLASS
  379. /* Cache the current thread in TLS for faster lookup. */
  380. scm_i_current_thread = t_ptr;
  381. #endif
  382. scm_i_pthread_mutex_lock (&thread_admin_mutex);
  383. t_ptr->next_thread = all_threads;
  384. all_threads = t_ptr;
  385. thread_count++;
  386. scm_i_pthread_mutex_unlock (&thread_admin_mutex);
  387. GC_enable ();
  388. }
  389. }
  390. /* Perform second stage of thread initialisation, in guile mode.
  391. */
  392. static void
  393. guilify_self_2 (SCM parent)
  394. {
  395. scm_i_thread *t = SCM_I_CURRENT_THREAD;
  396. t->guile_mode = 1;
  397. SCM_NEWSMOB (t->handle, scm_tc16_thread, t);
  398. t->continuation_root = scm_cons (t->handle, SCM_EOL);
  399. t->continuation_base = t->base;
  400. {
  401. size_t size = SCM_INLINE_GC_FREELIST_COUNT * sizeof (void *);
  402. t->freelists = scm_gc_malloc (size, "freelists");
  403. t->pointerless_freelists = scm_gc_malloc (size, "atomic freelists");
  404. }
  405. if (scm_is_true (parent))
  406. t->dynamic_state = scm_make_dynamic_state (parent);
  407. else
  408. t->dynamic_state = scm_i_make_initial_dynamic_state ();
  409. t->dynstack.base = scm_gc_malloc (16 * sizeof (scm_t_bits), "dynstack");
  410. t->dynstack.limit = t->dynstack.base + 16;
  411. t->dynstack.top = t->dynstack.base + SCM_DYNSTACK_HEADER_LEN;
  412. t->join_queue = make_queue ();
  413. t->block_asyncs = 0;
  414. /* See note in finalizers.c:queue_finalizer_async(). */
  415. GC_invoke_finalizers ();
  416. }
  417. /*** Fat mutexes */
  418. /* We implement our own mutex type since we want them to be 'fair', we
  419. want to do fancy things while waiting for them (like running
  420. asyncs) and we might want to add things that are nice for
  421. debugging.
  422. */
  423. typedef struct {
  424. scm_i_pthread_mutex_t lock;
  425. SCM owner;
  426. int level; /* how much the owner owns us. <= 1 for non-recursive mutexes */
  427. int recursive; /* allow recursive locking? */
  428. int unchecked_unlock; /* is it an error to unlock an unlocked mutex? */
  429. int allow_external_unlock; /* is it an error to unlock a mutex that is not
  430. owned by the current thread? */
  431. SCM waiting; /* the threads waiting for this mutex. */
  432. } fat_mutex;
  433. #define SCM_MUTEXP(x) SCM_SMOB_PREDICATE (scm_tc16_mutex, x)
  434. #define SCM_MUTEX_DATA(x) ((fat_mutex *) SCM_SMOB_DATA (x))
  435. static SCM
  436. call_cleanup (void *data)
  437. {
  438. SCM *proc_p = data;
  439. return scm_call_0 (*proc_p);
  440. }
  441. /* Perform thread tear-down, in guile mode.
  442. */
  443. static void *
  444. do_thread_exit (void *v)
  445. {
  446. scm_i_thread *t = (scm_i_thread *) v;
  447. if (!scm_is_false (t->cleanup_handler))
  448. {
  449. SCM ptr = t->cleanup_handler;
  450. t->cleanup_handler = SCM_BOOL_F;
  451. t->result = scm_internal_catch (SCM_BOOL_T,
  452. call_cleanup, &ptr,
  453. scm_handle_by_message_noexit, NULL);
  454. }
  455. scm_i_scm_pthread_mutex_lock (&t->admin_mutex);
  456. t->exited = 1;
  457. close (t->sleep_pipe[0]);
  458. close (t->sleep_pipe[1]);
  459. while (scm_is_true (unblock_from_queue (t->join_queue)))
  460. ;
  461. while (!scm_is_null (t->mutexes))
  462. {
  463. SCM mutex = scm_c_weak_vector_ref (scm_car (t->mutexes), 0);
  464. if (scm_is_true (mutex))
  465. {
  466. fat_mutex *m = SCM_MUTEX_DATA (mutex);
  467. scm_i_pthread_mutex_lock (&m->lock);
  468. /* Check whether T owns MUTEX. This is usually the case, unless
  469. T abandoned MUTEX; in that case, T is no longer its owner (see
  470. `fat_mutex_lock') but MUTEX is still in `t->mutexes'. */
  471. if (scm_is_eq (m->owner, t->handle))
  472. unblock_from_queue (m->waiting);
  473. scm_i_pthread_mutex_unlock (&m->lock);
  474. }
  475. t->mutexes = scm_cdr (t->mutexes);
  476. }
  477. scm_i_pthread_mutex_unlock (&t->admin_mutex);
  478. return NULL;
  479. }
  480. static void *
  481. do_thread_exit_trampoline (struct GC_stack_base *sb, void *v)
  482. {
  483. /* Won't hurt if we are already registered. */
  484. #if SCM_USE_PTHREAD_THREADS
  485. GC_register_my_thread (sb);
  486. #endif
  487. return scm_with_guile (do_thread_exit, v);
  488. }
  489. static void
  490. on_thread_exit (void *v)
  491. {
  492. /* This handler is executed in non-guile mode. */
  493. scm_i_thread *t = (scm_i_thread *) v, **tp;
  494. /* If we were canceled, we were unable to clear `t->guile_mode', so do
  495. it here. */
  496. t->guile_mode = 0;
  497. /* If this thread was cancelled while doing a cond wait, it will
  498. still have a mutex locked, so we unlock it here. */
  499. if (t->held_mutex)
  500. {
  501. scm_i_pthread_mutex_unlock (t->held_mutex);
  502. t->held_mutex = NULL;
  503. }
  504. /* Reinstate the current thread for purposes of scm_with_guile
  505. guile-mode cleanup handlers. Only really needed in the non-TLS
  506. case but it doesn't hurt to be consistent. */
  507. scm_i_pthread_setspecific (scm_i_thread_key, t);
  508. /* Scheme-level thread finalizers and other cleanup needs to happen in
  509. guile mode. */
  510. GC_call_with_stack_base (do_thread_exit_trampoline, t);
  511. /* Removing ourself from the list of all threads needs to happen in
  512. non-guile mode since all SCM values on our stack become
  513. unprotected once we are no longer in the list. */
  514. scm_i_pthread_mutex_lock (&thread_admin_mutex);
  515. for (tp = &all_threads; *tp; tp = &(*tp)->next_thread)
  516. if (*tp == t)
  517. {
  518. *tp = t->next_thread;
  519. /* GC-robust */
  520. t->next_thread = NULL;
  521. break;
  522. }
  523. thread_count--;
  524. /* If there's only one other thread, it could be the signal delivery
  525. thread, so we need to notify it to shut down by closing its read pipe.
  526. If it's not the signal delivery thread, then closing the read pipe isn't
  527. going to hurt. */
  528. if (thread_count <= 1)
  529. scm_i_close_signal_pipe ();
  530. scm_i_pthread_mutex_unlock (&thread_admin_mutex);
  531. scm_i_pthread_setspecific (scm_i_thread_key, NULL);
  532. if (t->vp)
  533. {
  534. scm_i_vm_free_stack (t->vp);
  535. t->vp = NULL;
  536. }
  537. #if SCM_USE_PTHREAD_THREADS
  538. GC_unregister_my_thread ();
  539. #endif
  540. }
  541. static scm_i_pthread_once_t init_thread_key_once = SCM_I_PTHREAD_ONCE_INIT;
  542. static void
  543. init_thread_key (void)
  544. {
  545. scm_i_pthread_key_create (&scm_i_thread_key, on_thread_exit);
  546. }
  547. /* Perform any initializations necessary to make the current thread
  548. known to Guile (via SCM_I_CURRENT_THREAD), initializing Guile itself,
  549. if necessary.
  550. BASE is the stack base to use with GC.
  551. PARENT is the dynamic state to use as the parent, ot SCM_BOOL_F in
  552. which case the default dynamic state is used.
  553. Returns zero when the thread was known to guile already; otherwise
  554. return 1.
  555. Note that it could be the case that the thread was known
  556. to Guile, but not in guile mode (because we are within a
  557. scm_without_guile call). Check SCM_I_CURRENT_THREAD->guile_mode to
  558. be sure. New threads are put into guile mode implicitly. */
  559. static int
  560. scm_i_init_thread_for_guile (struct GC_stack_base *base, SCM parent)
  561. {
  562. scm_i_pthread_once (&init_thread_key_once, init_thread_key);
  563. if (SCM_I_CURRENT_THREAD)
  564. {
  565. /* Thread is already known to Guile.
  566. */
  567. return 0;
  568. }
  569. else
  570. {
  571. /* This thread has not been guilified yet.
  572. */
  573. scm_i_pthread_mutex_lock (&scm_i_init_mutex);
  574. if (scm_initialized_p == 0)
  575. {
  576. /* First thread ever to enter Guile. Run the full
  577. initialization.
  578. */
  579. scm_i_init_guile (base);
  580. #if SCM_USE_PTHREAD_THREADS
  581. /* Allow other threads to come in later. */
  582. GC_allow_register_threads ();
  583. #endif
  584. scm_i_pthread_mutex_unlock (&scm_i_init_mutex);
  585. }
  586. else
  587. {
  588. /* Guile is already initialized, but this thread enters it for
  589. the first time. Only initialize this thread.
  590. */
  591. scm_i_pthread_mutex_unlock (&scm_i_init_mutex);
  592. /* Register this thread with libgc. */
  593. #if SCM_USE_PTHREAD_THREADS
  594. GC_register_my_thread (base);
  595. #endif
  596. guilify_self_1 (base);
  597. guilify_self_2 (parent);
  598. }
  599. return 1;
  600. }
  601. }
  602. void
  603. scm_init_guile ()
  604. {
  605. struct GC_stack_base stack_base;
  606. if (GC_get_stack_base (&stack_base) == GC_SUCCESS)
  607. scm_i_init_thread_for_guile (&stack_base,
  608. scm_i_default_dynamic_state);
  609. else
  610. {
  611. fprintf (stderr, "Failed to get stack base for current thread.\n");
  612. exit (EXIT_FAILURE);
  613. }
  614. }
  615. struct with_guile_args
  616. {
  617. GC_fn_type func;
  618. void *data;
  619. SCM parent;
  620. };
  621. static void *
  622. with_guile_trampoline (void *data)
  623. {
  624. struct with_guile_args *args = data;
  625. return scm_c_with_continuation_barrier (args->func, args->data);
  626. }
  627. static void *
  628. with_guile_and_parent (struct GC_stack_base *base, void *data)
  629. {
  630. void *res;
  631. int new_thread;
  632. scm_i_thread *t;
  633. struct with_guile_args *args = data;
  634. new_thread = scm_i_init_thread_for_guile (base, args->parent);
  635. t = SCM_I_CURRENT_THREAD;
  636. if (new_thread)
  637. {
  638. /* We are in Guile mode. */
  639. assert (t->guile_mode);
  640. res = scm_c_with_continuation_barrier (args->func, args->data);
  641. /* Leave Guile mode. */
  642. t->guile_mode = 0;
  643. }
  644. else if (t->guile_mode)
  645. {
  646. /* Already in Guile mode. */
  647. res = scm_c_with_continuation_barrier (args->func, args->data);
  648. }
  649. else
  650. {
  651. /* We are not in Guile mode, either because we are not within a
  652. scm_with_guile, or because we are within a scm_without_guile.
  653. This call to scm_with_guile() could happen from anywhere on the
  654. stack, and in particular lower on the stack than when it was
  655. when this thread was first guilified. Thus, `base' must be
  656. updated. */
  657. #if SCM_STACK_GROWS_UP
  658. if (SCM_STACK_PTR (base->mem_base) < t->base)
  659. t->base = SCM_STACK_PTR (base->mem_base);
  660. #else
  661. if (SCM_STACK_PTR (base->mem_base) > t->base)
  662. t->base = SCM_STACK_PTR (base->mem_base);
  663. #endif
  664. t->guile_mode = 1;
  665. res = GC_call_with_gc_active (with_guile_trampoline, args);
  666. t->guile_mode = 0;
  667. }
  668. return res;
  669. }
  670. static void *
  671. scm_i_with_guile_and_parent (void *(*func)(void *), void *data, SCM parent)
  672. {
  673. struct with_guile_args args;
  674. args.func = func;
  675. args.data = data;
  676. args.parent = parent;
  677. return GC_call_with_stack_base (with_guile_and_parent, &args);
  678. }
  679. void *
  680. scm_with_guile (void *(*func)(void *), void *data)
  681. {
  682. return scm_i_with_guile_and_parent (func, data,
  683. scm_i_default_dynamic_state);
  684. }
  685. void *
  686. scm_without_guile (void *(*func)(void *), void *data)
  687. {
  688. void *result;
  689. scm_i_thread *t = SCM_I_CURRENT_THREAD;
  690. if (t->guile_mode)
  691. {
  692. SCM_I_CURRENT_THREAD->guile_mode = 0;
  693. result = GC_do_blocking (func, data);
  694. SCM_I_CURRENT_THREAD->guile_mode = 1;
  695. }
  696. else
  697. /* Otherwise we're not in guile mode, so nothing to do. */
  698. result = func (data);
  699. return result;
  700. }
  701. /*** Thread creation */
  702. typedef struct {
  703. SCM parent;
  704. SCM thunk;
  705. SCM handler;
  706. SCM thread;
  707. scm_i_pthread_mutex_t mutex;
  708. scm_i_pthread_cond_t cond;
  709. } launch_data;
  710. static void *
  711. really_launch (void *d)
  712. {
  713. launch_data *data = (launch_data *)d;
  714. SCM thunk = data->thunk, handler = data->handler;
  715. scm_i_thread *t;
  716. t = SCM_I_CURRENT_THREAD;
  717. scm_i_scm_pthread_mutex_lock (&data->mutex);
  718. data->thread = scm_current_thread ();
  719. scm_i_pthread_cond_signal (&data->cond);
  720. scm_i_pthread_mutex_unlock (&data->mutex);
  721. if (SCM_UNBNDP (handler))
  722. t->result = scm_call_0 (thunk);
  723. else
  724. t->result = scm_catch (SCM_BOOL_T, thunk, handler);
  725. return 0;
  726. }
  727. static void *
  728. launch_thread (void *d)
  729. {
  730. launch_data *data = (launch_data *)d;
  731. scm_i_pthread_detach (scm_i_pthread_self ());
  732. scm_i_with_guile_and_parent (really_launch, d, data->parent);
  733. return NULL;
  734. }
  735. SCM_DEFINE (scm_call_with_new_thread, "call-with-new-thread", 1, 1, 0,
  736. (SCM thunk, SCM handler),
  737. "Call @code{thunk} in a new thread and with a new dynamic state,\n"
  738. "returning a new thread object representing the thread. The procedure\n"
  739. "@var{thunk} is called via @code{with-continuation-barrier}.\n"
  740. "\n"
  741. "When @var{handler} is specified, then @var{thunk} is called from\n"
  742. "within a @code{catch} with tag @code{#t} that has @var{handler} as its\n"
  743. "handler. This catch is established inside the continuation barrier.\n"
  744. "\n"
  745. "Once @var{thunk} or @var{handler} returns, the return value is made\n"
  746. "the @emph{exit value} of the thread and the thread is terminated.")
  747. #define FUNC_NAME s_scm_call_with_new_thread
  748. {
  749. launch_data data;
  750. scm_i_pthread_t id;
  751. int err;
  752. SCM_ASSERT (scm_is_true (scm_thunk_p (thunk)), thunk, SCM_ARG1, FUNC_NAME);
  753. SCM_ASSERT (SCM_UNBNDP (handler) || scm_is_true (scm_procedure_p (handler)),
  754. handler, SCM_ARG2, FUNC_NAME);
  755. GC_collect_a_little ();
  756. data.parent = scm_current_dynamic_state ();
  757. data.thunk = thunk;
  758. data.handler = handler;
  759. data.thread = SCM_BOOL_F;
  760. scm_i_pthread_mutex_init (&data.mutex, NULL);
  761. scm_i_pthread_cond_init (&data.cond, NULL);
  762. scm_i_scm_pthread_mutex_lock (&data.mutex);
  763. err = scm_i_pthread_create (&id, NULL, launch_thread, &data);
  764. if (err)
  765. {
  766. scm_i_pthread_mutex_unlock (&data.mutex);
  767. errno = err;
  768. scm_syserror (NULL);
  769. }
  770. while (scm_is_false (data.thread))
  771. scm_i_scm_pthread_cond_wait (&data.cond, &data.mutex);
  772. scm_i_pthread_mutex_unlock (&data.mutex);
  773. return data.thread;
  774. }
  775. #undef FUNC_NAME
  776. typedef struct {
  777. SCM parent;
  778. scm_t_catch_body body;
  779. void *body_data;
  780. scm_t_catch_handler handler;
  781. void *handler_data;
  782. SCM thread;
  783. scm_i_pthread_mutex_t mutex;
  784. scm_i_pthread_cond_t cond;
  785. } spawn_data;
  786. static void *
  787. really_spawn (void *d)
  788. {
  789. spawn_data *data = (spawn_data *)d;
  790. scm_t_catch_body body = data->body;
  791. void *body_data = data->body_data;
  792. scm_t_catch_handler handler = data->handler;
  793. void *handler_data = data->handler_data;
  794. scm_i_thread *t = SCM_I_CURRENT_THREAD;
  795. scm_i_scm_pthread_mutex_lock (&data->mutex);
  796. data->thread = scm_current_thread ();
  797. scm_i_pthread_cond_signal (&data->cond);
  798. scm_i_pthread_mutex_unlock (&data->mutex);
  799. if (handler == NULL)
  800. t->result = body (body_data);
  801. else
  802. t->result = scm_internal_catch (SCM_BOOL_T,
  803. body, body_data,
  804. handler, handler_data);
  805. return 0;
  806. }
  807. static void *
  808. spawn_thread (void *d)
  809. {
  810. spawn_data *data = (spawn_data *)d;
  811. scm_i_pthread_detach (scm_i_pthread_self ());
  812. scm_i_with_guile_and_parent (really_spawn, d, data->parent);
  813. return NULL;
  814. }
  815. SCM
  816. scm_spawn_thread (scm_t_catch_body body, void *body_data,
  817. scm_t_catch_handler handler, void *handler_data)
  818. {
  819. spawn_data data;
  820. scm_i_pthread_t id;
  821. int err;
  822. data.parent = scm_current_dynamic_state ();
  823. data.body = body;
  824. data.body_data = body_data;
  825. data.handler = handler;
  826. data.handler_data = handler_data;
  827. data.thread = SCM_BOOL_F;
  828. scm_i_pthread_mutex_init (&data.mutex, NULL);
  829. scm_i_pthread_cond_init (&data.cond, NULL);
  830. scm_i_scm_pthread_mutex_lock (&data.mutex);
  831. err = scm_i_pthread_create (&id, NULL, spawn_thread, &data);
  832. if (err)
  833. {
  834. scm_i_pthread_mutex_unlock (&data.mutex);
  835. errno = err;
  836. scm_syserror (NULL);
  837. }
  838. while (scm_is_false (data.thread))
  839. scm_i_scm_pthread_cond_wait (&data.cond, &data.mutex);
  840. scm_i_pthread_mutex_unlock (&data.mutex);
  841. assert (SCM_I_IS_THREAD (data.thread));
  842. return data.thread;
  843. }
  844. SCM_DEFINE (scm_yield, "yield", 0, 0, 0,
  845. (),
  846. "Move the calling thread to the end of the scheduling queue.")
  847. #define FUNC_NAME s_scm_yield
  848. {
  849. return scm_from_bool (scm_i_sched_yield ());
  850. }
  851. #undef FUNC_NAME
  852. /* Some systems, notably Android, lack 'pthread_cancel'. Don't provide
  853. 'cancel-thread' on these systems. */
  854. #if !SCM_USE_PTHREAD_THREADS || defined HAVE_PTHREAD_CANCEL
  855. SCM_DEFINE (scm_cancel_thread, "cancel-thread", 1, 0, 0,
  856. (SCM thread),
  857. "Asynchronously force the target @var{thread} to terminate. @var{thread} "
  858. "cannot be the current thread, and if @var{thread} has already terminated or "
  859. "been signaled to terminate, this function is a no-op.")
  860. #define FUNC_NAME s_scm_cancel_thread
  861. {
  862. scm_i_thread *t = NULL;
  863. SCM_VALIDATE_THREAD (1, thread);
  864. t = SCM_I_THREAD_DATA (thread);
  865. scm_i_scm_pthread_mutex_lock (&t->admin_mutex);
  866. if (!t->canceled)
  867. {
  868. t->canceled = 1;
  869. scm_i_pthread_mutex_unlock (&t->admin_mutex);
  870. scm_i_pthread_cancel (t->pthread);
  871. }
  872. else
  873. scm_i_pthread_mutex_unlock (&t->admin_mutex);
  874. return SCM_UNSPECIFIED;
  875. }
  876. #undef FUNC_NAME
  877. #endif
  878. SCM_DEFINE (scm_set_thread_cleanup_x, "set-thread-cleanup!", 2, 0, 0,
  879. (SCM thread, SCM proc),
  880. "Set the thunk @var{proc} as the cleanup handler for the thread @var{thread}. "
  881. "This handler will be called when the thread exits.")
  882. #define FUNC_NAME s_scm_set_thread_cleanup_x
  883. {
  884. scm_i_thread *t;
  885. SCM_VALIDATE_THREAD (1, thread);
  886. if (!scm_is_false (proc))
  887. SCM_VALIDATE_THUNK (2, proc);
  888. t = SCM_I_THREAD_DATA (thread);
  889. scm_i_pthread_mutex_lock (&t->admin_mutex);
  890. if (!(t->exited || t->canceled))
  891. t->cleanup_handler = proc;
  892. scm_i_pthread_mutex_unlock (&t->admin_mutex);
  893. return SCM_UNSPECIFIED;
  894. }
  895. #undef FUNC_NAME
  896. SCM_DEFINE (scm_thread_cleanup, "thread-cleanup", 1, 0, 0,
  897. (SCM thread),
  898. "Return the cleanup handler installed for the thread @var{thread}.")
  899. #define FUNC_NAME s_scm_thread_cleanup
  900. {
  901. scm_i_thread *t;
  902. SCM ret;
  903. SCM_VALIDATE_THREAD (1, thread);
  904. t = SCM_I_THREAD_DATA (thread);
  905. scm_i_pthread_mutex_lock (&t->admin_mutex);
  906. ret = (t->exited || t->canceled) ? SCM_BOOL_F : t->cleanup_handler;
  907. scm_i_pthread_mutex_unlock (&t->admin_mutex);
  908. return ret;
  909. }
  910. #undef FUNC_NAME
  911. SCM scm_join_thread (SCM thread)
  912. {
  913. return scm_join_thread_timed (thread, SCM_UNDEFINED, SCM_UNDEFINED);
  914. }
  915. SCM_DEFINE (scm_join_thread_timed, "join-thread", 1, 2, 0,
  916. (SCM thread, SCM timeout, SCM timeoutval),
  917. "Suspend execution of the calling thread until the target @var{thread} "
  918. "terminates, unless the target @var{thread} has already terminated. ")
  919. #define FUNC_NAME s_scm_join_thread_timed
  920. {
  921. scm_i_thread *t;
  922. scm_t_timespec ctimeout, *timeout_ptr = NULL;
  923. SCM res = SCM_BOOL_F;
  924. if (! (SCM_UNBNDP (timeoutval)))
  925. res = timeoutval;
  926. SCM_VALIDATE_THREAD (1, thread);
  927. if (scm_is_eq (scm_current_thread (), thread))
  928. SCM_MISC_ERROR ("cannot join the current thread", SCM_EOL);
  929. t = SCM_I_THREAD_DATA (thread);
  930. scm_i_scm_pthread_mutex_lock (&t->admin_mutex);
  931. if (! SCM_UNBNDP (timeout))
  932. {
  933. to_timespec (timeout, &ctimeout);
  934. timeout_ptr = &ctimeout;
  935. }
  936. if (t->exited)
  937. res = t->result;
  938. else
  939. {
  940. while (1)
  941. {
  942. int err = block_self (t->join_queue, thread, &t->admin_mutex,
  943. timeout_ptr);
  944. if (err == 0)
  945. {
  946. if (t->exited)
  947. {
  948. res = t->result;
  949. break;
  950. }
  951. }
  952. else if (err == ETIMEDOUT)
  953. break;
  954. scm_i_pthread_mutex_unlock (&t->admin_mutex);
  955. SCM_TICK;
  956. scm_i_scm_pthread_mutex_lock (&t->admin_mutex);
  957. /* Check for exit again, since we just released and
  958. reacquired the admin mutex, before the next block_self
  959. call (which would block forever if t has already
  960. exited). */
  961. if (t->exited)
  962. {
  963. res = t->result;
  964. break;
  965. }
  966. }
  967. }
  968. scm_i_pthread_mutex_unlock (&t->admin_mutex);
  969. return res;
  970. }
  971. #undef FUNC_NAME
  972. SCM_DEFINE (scm_thread_p, "thread?", 1, 0, 0,
  973. (SCM obj),
  974. "Return @code{#t} if @var{obj} is a thread.")
  975. #define FUNC_NAME s_scm_thread_p
  976. {
  977. return SCM_I_IS_THREAD(obj) ? SCM_BOOL_T : SCM_BOOL_F;
  978. }
  979. #undef FUNC_NAME
  980. static int
  981. fat_mutex_print (SCM mx, SCM port, scm_print_state *pstate SCM_UNUSED)
  982. {
  983. fat_mutex *m = SCM_MUTEX_DATA (mx);
  984. scm_puts_unlocked ("#<mutex ", port);
  985. scm_uintprint ((scm_t_bits)m, 16, port);
  986. scm_puts_unlocked (">", port);
  987. return 1;
  988. }
  989. static SCM
  990. make_fat_mutex (int recursive, int unchecked_unlock, int external_unlock)
  991. {
  992. fat_mutex *m;
  993. SCM mx;
  994. scm_i_pthread_mutex_t lock = SCM_I_PTHREAD_MUTEX_INITIALIZER;
  995. m = scm_gc_malloc (sizeof (fat_mutex), "mutex");
  996. /* Because PTHREAD_MUTEX_INITIALIZER is static, it's plain old data,
  997. and so we can just copy it. */
  998. memcpy (&m->lock, &lock, sizeof (m->lock));
  999. m->owner = SCM_BOOL_F;
  1000. m->level = 0;
  1001. m->recursive = recursive;
  1002. m->unchecked_unlock = unchecked_unlock;
  1003. m->allow_external_unlock = external_unlock;
  1004. m->waiting = SCM_EOL;
  1005. SCM_NEWSMOB (mx, scm_tc16_mutex, (scm_t_bits) m);
  1006. m->waiting = make_queue ();
  1007. return mx;
  1008. }
  1009. SCM scm_make_mutex (void)
  1010. {
  1011. return scm_make_mutex_with_flags (SCM_EOL);
  1012. }
  1013. SCM_SYMBOL (unchecked_unlock_sym, "unchecked-unlock");
  1014. SCM_SYMBOL (allow_external_unlock_sym, "allow-external-unlock");
  1015. SCM_SYMBOL (recursive_sym, "recursive");
  1016. SCM_DEFINE (scm_make_mutex_with_flags, "make-mutex", 0, 0, 1,
  1017. (SCM flags),
  1018. "Create a new mutex. ")
  1019. #define FUNC_NAME s_scm_make_mutex_with_flags
  1020. {
  1021. int unchecked_unlock = 0, external_unlock = 0, recursive = 0;
  1022. SCM ptr = flags;
  1023. while (! scm_is_null (ptr))
  1024. {
  1025. SCM flag = SCM_CAR (ptr);
  1026. if (scm_is_eq (flag, unchecked_unlock_sym))
  1027. unchecked_unlock = 1;
  1028. else if (scm_is_eq (flag, allow_external_unlock_sym))
  1029. external_unlock = 1;
  1030. else if (scm_is_eq (flag, recursive_sym))
  1031. recursive = 1;
  1032. else
  1033. SCM_MISC_ERROR ("unsupported mutex option: ~a", scm_list_1 (flag));
  1034. ptr = SCM_CDR (ptr);
  1035. }
  1036. return make_fat_mutex (recursive, unchecked_unlock, external_unlock);
  1037. }
  1038. #undef FUNC_NAME
  1039. SCM_DEFINE (scm_make_recursive_mutex, "make-recursive-mutex", 0, 0, 0,
  1040. (void),
  1041. "Create a new recursive mutex. ")
  1042. #define FUNC_NAME s_scm_make_recursive_mutex
  1043. {
  1044. return make_fat_mutex (1, 0, 0);
  1045. }
  1046. #undef FUNC_NAME
  1047. SCM_SYMBOL (scm_abandoned_mutex_error_key, "abandoned-mutex-error");
  1048. static SCM
  1049. fat_mutex_lock (SCM mutex, scm_t_timespec *timeout, SCM owner, int *ret)
  1050. {
  1051. fat_mutex *m = SCM_MUTEX_DATA (mutex);
  1052. SCM new_owner = SCM_UNBNDP (owner) ? scm_current_thread() : owner;
  1053. SCM err = SCM_BOOL_F;
  1054. struct timeval current_time;
  1055. scm_i_scm_pthread_mutex_lock (&m->lock);
  1056. while (1)
  1057. {
  1058. if (m->level == 0)
  1059. {
  1060. m->owner = new_owner;
  1061. m->level++;
  1062. if (SCM_I_IS_THREAD (new_owner))
  1063. {
  1064. scm_i_thread *t = SCM_I_THREAD_DATA (new_owner);
  1065. /* FIXME: The order in which `t->admin_mutex' and
  1066. `m->lock' are taken differs from that in
  1067. `on_thread_exit', potentially leading to deadlocks. */
  1068. scm_i_pthread_mutex_lock (&t->admin_mutex);
  1069. /* Only keep a weak reference to MUTEX so that it's not
  1070. retained when not referenced elsewhere (bug #27450).
  1071. The weak pair itself is eventually removed when MUTEX
  1072. is unlocked. Note that `t->mutexes' lists mutexes
  1073. currently held by T, so it should be small. */
  1074. t->mutexes = scm_cons (scm_make_weak_vector (SCM_INUM1, mutex),
  1075. t->mutexes);
  1076. scm_i_pthread_mutex_unlock (&t->admin_mutex);
  1077. }
  1078. *ret = 1;
  1079. break;
  1080. }
  1081. else if (SCM_I_IS_THREAD (m->owner) && scm_c_thread_exited_p (m->owner))
  1082. {
  1083. m->owner = new_owner;
  1084. err = scm_cons (scm_abandoned_mutex_error_key,
  1085. scm_from_locale_string ("lock obtained on abandoned "
  1086. "mutex"));
  1087. *ret = 1;
  1088. break;
  1089. }
  1090. else if (scm_is_eq (m->owner, new_owner))
  1091. {
  1092. if (m->recursive)
  1093. {
  1094. m->level++;
  1095. *ret = 1;
  1096. }
  1097. else
  1098. {
  1099. err = scm_cons (scm_misc_error_key,
  1100. scm_from_locale_string ("mutex already locked "
  1101. "by thread"));
  1102. *ret = 0;
  1103. }
  1104. break;
  1105. }
  1106. else
  1107. {
  1108. if (timeout != NULL)
  1109. {
  1110. gettimeofday (&current_time, NULL);
  1111. if (current_time.tv_sec > timeout->tv_sec ||
  1112. (current_time.tv_sec == timeout->tv_sec &&
  1113. current_time.tv_usec * 1000 > timeout->tv_nsec))
  1114. {
  1115. *ret = 0;
  1116. break;
  1117. }
  1118. }
  1119. block_self (m->waiting, mutex, &m->lock, timeout);
  1120. scm_i_pthread_mutex_unlock (&m->lock);
  1121. SCM_TICK;
  1122. scm_i_scm_pthread_mutex_lock (&m->lock);
  1123. }
  1124. }
  1125. scm_i_pthread_mutex_unlock (&m->lock);
  1126. return err;
  1127. }
  1128. SCM scm_lock_mutex (SCM mx)
  1129. {
  1130. return scm_lock_mutex_timed (mx, SCM_UNDEFINED, SCM_UNDEFINED);
  1131. }
  1132. SCM_DEFINE (scm_lock_mutex_timed, "lock-mutex", 1, 2, 0,
  1133. (SCM m, SCM timeout, SCM owner),
  1134. "Lock mutex @var{m}. If the mutex is already locked, the calling\n"
  1135. "thread blocks until the mutex becomes available. The function\n"
  1136. "returns when the calling thread owns the lock on @var{m}.\n"
  1137. "Locking a mutex that a thread already owns will succeed right\n"
  1138. "away and will not block the thread. That is, Guile's mutexes\n"
  1139. "are @emph{recursive}.")
  1140. #define FUNC_NAME s_scm_lock_mutex_timed
  1141. {
  1142. SCM exception;
  1143. int ret = 0;
  1144. scm_t_timespec cwaittime, *waittime = NULL;
  1145. SCM_VALIDATE_MUTEX (1, m);
  1146. if (! SCM_UNBNDP (timeout) && ! scm_is_false (timeout))
  1147. {
  1148. to_timespec (timeout, &cwaittime);
  1149. waittime = &cwaittime;
  1150. }
  1151. if (!SCM_UNBNDP (owner) && !scm_is_false (owner))
  1152. SCM_VALIDATE_THREAD (3, owner);
  1153. exception = fat_mutex_lock (m, waittime, owner, &ret);
  1154. if (!scm_is_false (exception))
  1155. scm_ithrow (SCM_CAR (exception), scm_list_1 (SCM_CDR (exception)), 1);
  1156. return ret ? SCM_BOOL_T : SCM_BOOL_F;
  1157. }
  1158. #undef FUNC_NAME
  1159. static void
  1160. lock_mutex_return_void (SCM mx)
  1161. {
  1162. (void) scm_lock_mutex (mx);
  1163. }
  1164. static void
  1165. unlock_mutex_return_void (SCM mx)
  1166. {
  1167. (void) scm_unlock_mutex (mx);
  1168. }
  1169. void
  1170. scm_dynwind_lock_mutex (SCM mutex)
  1171. {
  1172. scm_dynwind_unwind_handler_with_scm (unlock_mutex_return_void, mutex,
  1173. SCM_F_WIND_EXPLICITLY);
  1174. scm_dynwind_rewind_handler_with_scm (lock_mutex_return_void, mutex,
  1175. SCM_F_WIND_EXPLICITLY);
  1176. }
  1177. SCM_DEFINE (scm_try_mutex, "try-mutex", 1, 0, 0,
  1178. (SCM mutex),
  1179. "Try to lock @var{mutex}. If the mutex is already locked by someone "
  1180. "else, return @code{#f}. Else lock the mutex and return @code{#t}. ")
  1181. #define FUNC_NAME s_scm_try_mutex
  1182. {
  1183. SCM exception;
  1184. int ret = 0;
  1185. scm_t_timespec cwaittime, *waittime = NULL;
  1186. SCM_VALIDATE_MUTEX (1, mutex);
  1187. to_timespec (scm_from_int(0), &cwaittime);
  1188. waittime = &cwaittime;
  1189. exception = fat_mutex_lock (mutex, waittime, SCM_UNDEFINED, &ret);
  1190. if (!scm_is_false (exception))
  1191. scm_ithrow (SCM_CAR (exception), scm_list_1 (SCM_CDR (exception)), 1);
  1192. return ret ? SCM_BOOL_T : SCM_BOOL_F;
  1193. }
  1194. #undef FUNC_NAME
  1195. /*** Fat condition variables */
  1196. typedef struct {
  1197. scm_i_pthread_mutex_t lock;
  1198. SCM waiting; /* the threads waiting for this condition. */
  1199. } fat_cond;
  1200. #define SCM_CONDVARP(x) SCM_SMOB_PREDICATE (scm_tc16_condvar, x)
  1201. #define SCM_CONDVAR_DATA(x) ((fat_cond *) SCM_SMOB_DATA (x))
  1202. static void
  1203. remove_mutex_from_thread (SCM mutex, scm_i_thread *t)
  1204. {
  1205. SCM walk, prev;
  1206. for (prev = SCM_BOOL_F, walk = t->mutexes; scm_is_pair (walk);
  1207. walk = SCM_CDR (walk))
  1208. {
  1209. if (scm_is_eq (mutex, scm_c_weak_vector_ref (SCM_CAR (walk), 0)))
  1210. {
  1211. if (scm_is_pair (prev))
  1212. SCM_SETCDR (prev, SCM_CDR (walk));
  1213. else
  1214. t->mutexes = SCM_CDR (walk);
  1215. break;
  1216. }
  1217. }
  1218. }
  1219. static int
  1220. fat_mutex_unlock (SCM mutex, SCM cond,
  1221. const scm_t_timespec *waittime, int relock)
  1222. {
  1223. SCM owner;
  1224. fat_mutex *m = SCM_MUTEX_DATA (mutex);
  1225. fat_cond *c = NULL;
  1226. scm_i_thread *t = SCM_I_CURRENT_THREAD;
  1227. int err = 0, ret = 0;
  1228. scm_i_scm_pthread_mutex_lock (&m->lock);
  1229. owner = m->owner;
  1230. if (!scm_is_eq (owner, t->handle))
  1231. {
  1232. if (m->level == 0)
  1233. {
  1234. if (!m->unchecked_unlock)
  1235. {
  1236. scm_i_pthread_mutex_unlock (&m->lock);
  1237. scm_misc_error (NULL, "mutex not locked", SCM_EOL);
  1238. }
  1239. owner = t->handle;
  1240. }
  1241. else if (!m->allow_external_unlock)
  1242. {
  1243. scm_i_pthread_mutex_unlock (&m->lock);
  1244. scm_misc_error (NULL, "mutex not locked by current thread", SCM_EOL);
  1245. }
  1246. }
  1247. if (! (SCM_UNBNDP (cond)))
  1248. {
  1249. c = SCM_CONDVAR_DATA (cond);
  1250. while (1)
  1251. {
  1252. int brk = 0;
  1253. if (m->level > 0)
  1254. m->level--;
  1255. if (m->level == 0)
  1256. {
  1257. /* Change the owner of MUTEX. */
  1258. remove_mutex_from_thread (mutex, t);
  1259. m->owner = unblock_from_queue (m->waiting);
  1260. }
  1261. t->block_asyncs++;
  1262. err = block_self (c->waiting, cond, &m->lock, waittime);
  1263. scm_i_pthread_mutex_unlock (&m->lock);
  1264. if (err == 0)
  1265. {
  1266. ret = 1;
  1267. brk = 1;
  1268. }
  1269. else if (err == ETIMEDOUT)
  1270. {
  1271. ret = 0;
  1272. brk = 1;
  1273. }
  1274. else if (err != EINTR)
  1275. {
  1276. errno = err;
  1277. scm_syserror (NULL);
  1278. }
  1279. if (brk)
  1280. {
  1281. if (relock)
  1282. scm_lock_mutex_timed (mutex, SCM_UNDEFINED, owner);
  1283. t->block_asyncs--;
  1284. break;
  1285. }
  1286. t->block_asyncs--;
  1287. scm_async_tick ();
  1288. scm_remember_upto_here_2 (cond, mutex);
  1289. scm_i_scm_pthread_mutex_lock (&m->lock);
  1290. }
  1291. }
  1292. else
  1293. {
  1294. if (m->level > 0)
  1295. m->level--;
  1296. if (m->level == 0)
  1297. {
  1298. /* Change the owner of MUTEX. */
  1299. remove_mutex_from_thread (mutex, t);
  1300. m->owner = unblock_from_queue (m->waiting);
  1301. }
  1302. scm_i_pthread_mutex_unlock (&m->lock);
  1303. ret = 1;
  1304. }
  1305. return ret;
  1306. }
  1307. SCM scm_unlock_mutex (SCM mx)
  1308. {
  1309. return scm_unlock_mutex_timed (mx, SCM_UNDEFINED, SCM_UNDEFINED);
  1310. }
  1311. SCM_DEFINE (scm_unlock_mutex_timed, "unlock-mutex", 1, 2, 0,
  1312. (SCM mx, SCM cond, SCM timeout),
  1313. "Unlocks @var{mutex} if the calling thread owns the lock on "
  1314. "@var{mutex}. Calling unlock-mutex on a mutex not owned by the current "
  1315. "thread results in undefined behaviour. Once a mutex has been unlocked, "
  1316. "one thread blocked on @var{mutex} is awakened and grabs the mutex "
  1317. "lock. Every call to @code{lock-mutex} by this thread must be matched "
  1318. "with a call to @code{unlock-mutex}. Only the last call to "
  1319. "@code{unlock-mutex} will actually unlock the mutex. ")
  1320. #define FUNC_NAME s_scm_unlock_mutex_timed
  1321. {
  1322. scm_t_timespec cwaittime, *waittime = NULL;
  1323. SCM_VALIDATE_MUTEX (1, mx);
  1324. if (! (SCM_UNBNDP (cond)))
  1325. {
  1326. SCM_VALIDATE_CONDVAR (2, cond);
  1327. if (! SCM_UNBNDP (timeout) && ! scm_is_false (timeout))
  1328. {
  1329. to_timespec (timeout, &cwaittime);
  1330. waittime = &cwaittime;
  1331. }
  1332. }
  1333. return fat_mutex_unlock (mx, cond, waittime, 0) ? SCM_BOOL_T : SCM_BOOL_F;
  1334. }
  1335. #undef FUNC_NAME
  1336. SCM_DEFINE (scm_mutex_p, "mutex?", 1, 0, 0,
  1337. (SCM obj),
  1338. "Return @code{#t} if @var{obj} is a mutex.")
  1339. #define FUNC_NAME s_scm_mutex_p
  1340. {
  1341. return SCM_MUTEXP (obj) ? SCM_BOOL_T : SCM_BOOL_F;
  1342. }
  1343. #undef FUNC_NAME
  1344. SCM_DEFINE (scm_mutex_owner, "mutex-owner", 1, 0, 0,
  1345. (SCM mx),
  1346. "Return the thread owning @var{mx}, or @code{#f}.")
  1347. #define FUNC_NAME s_scm_mutex_owner
  1348. {
  1349. SCM owner;
  1350. fat_mutex *m = NULL;
  1351. SCM_VALIDATE_MUTEX (1, mx);
  1352. m = SCM_MUTEX_DATA (mx);
  1353. scm_i_pthread_mutex_lock (&m->lock);
  1354. owner = m->owner;
  1355. scm_i_pthread_mutex_unlock (&m->lock);
  1356. return owner;
  1357. }
  1358. #undef FUNC_NAME
  1359. SCM_DEFINE (scm_mutex_level, "mutex-level", 1, 0, 0,
  1360. (SCM mx),
  1361. "Return the lock level of mutex @var{mx}.")
  1362. #define FUNC_NAME s_scm_mutex_level
  1363. {
  1364. SCM_VALIDATE_MUTEX (1, mx);
  1365. return scm_from_int (SCM_MUTEX_DATA(mx)->level);
  1366. }
  1367. #undef FUNC_NAME
  1368. SCM_DEFINE (scm_mutex_locked_p, "mutex-locked?", 1, 0, 0,
  1369. (SCM mx),
  1370. "Returns @code{#t} if the mutex @var{mx} is locked.")
  1371. #define FUNC_NAME s_scm_mutex_locked_p
  1372. {
  1373. SCM_VALIDATE_MUTEX (1, mx);
  1374. return SCM_MUTEX_DATA (mx)->level > 0 ? SCM_BOOL_T : SCM_BOOL_F;
  1375. }
  1376. #undef FUNC_NAME
  1377. static int
  1378. fat_cond_print (SCM cv, SCM port, scm_print_state *pstate SCM_UNUSED)
  1379. {
  1380. fat_cond *c = SCM_CONDVAR_DATA (cv);
  1381. scm_puts_unlocked ("#<condition-variable ", port);
  1382. scm_uintprint ((scm_t_bits)c, 16, port);
  1383. scm_puts_unlocked (">", port);
  1384. return 1;
  1385. }
  1386. SCM_DEFINE (scm_make_condition_variable, "make-condition-variable", 0, 0, 0,
  1387. (void),
  1388. "Make a new condition variable.")
  1389. #define FUNC_NAME s_scm_make_condition_variable
  1390. {
  1391. fat_cond *c;
  1392. SCM cv;
  1393. c = scm_gc_malloc (sizeof (fat_cond), "condition variable");
  1394. c->waiting = SCM_EOL;
  1395. SCM_NEWSMOB (cv, scm_tc16_condvar, (scm_t_bits) c);
  1396. c->waiting = make_queue ();
  1397. return cv;
  1398. }
  1399. #undef FUNC_NAME
  1400. SCM_DEFINE (scm_timed_wait_condition_variable, "wait-condition-variable", 2, 1, 0,
  1401. (SCM cv, SCM mx, SCM t),
  1402. "Wait until condition variable @var{cv} has been signalled. While waiting, "
  1403. "mutex @var{mx} is atomically unlocked (as with @code{unlock-mutex}) and "
  1404. "is locked again when this function returns. When @var{t} is given, "
  1405. "it specifies a point in time where the waiting should be aborted. It "
  1406. "can be either a integer as returned by @code{current-time} or a pair "
  1407. "as returned by @code{gettimeofday}. When the waiting is aborted the "
  1408. "mutex is locked and @code{#f} is returned. When the condition "
  1409. "variable is in fact signalled, the mutex is also locked and @code{#t} "
  1410. "is returned. ")
  1411. #define FUNC_NAME s_scm_timed_wait_condition_variable
  1412. {
  1413. scm_t_timespec waittime, *waitptr = NULL;
  1414. SCM_VALIDATE_CONDVAR (1, cv);
  1415. SCM_VALIDATE_MUTEX (2, mx);
  1416. if (!SCM_UNBNDP (t))
  1417. {
  1418. to_timespec (t, &waittime);
  1419. waitptr = &waittime;
  1420. }
  1421. return fat_mutex_unlock (mx, cv, waitptr, 1) ? SCM_BOOL_T : SCM_BOOL_F;
  1422. }
  1423. #undef FUNC_NAME
  1424. static void
  1425. fat_cond_signal (fat_cond *c)
  1426. {
  1427. unblock_from_queue (c->waiting);
  1428. }
  1429. SCM_DEFINE (scm_signal_condition_variable, "signal-condition-variable", 1, 0, 0,
  1430. (SCM cv),
  1431. "Wake up one thread that is waiting for @var{cv}")
  1432. #define FUNC_NAME s_scm_signal_condition_variable
  1433. {
  1434. SCM_VALIDATE_CONDVAR (1, cv);
  1435. fat_cond_signal (SCM_CONDVAR_DATA (cv));
  1436. return SCM_BOOL_T;
  1437. }
  1438. #undef FUNC_NAME
  1439. static void
  1440. fat_cond_broadcast (fat_cond *c)
  1441. {
  1442. while (scm_is_true (unblock_from_queue (c->waiting)))
  1443. ;
  1444. }
  1445. SCM_DEFINE (scm_broadcast_condition_variable, "broadcast-condition-variable", 1, 0, 0,
  1446. (SCM cv),
  1447. "Wake up all threads that are waiting for @var{cv}. ")
  1448. #define FUNC_NAME s_scm_broadcast_condition_variable
  1449. {
  1450. SCM_VALIDATE_CONDVAR (1, cv);
  1451. fat_cond_broadcast (SCM_CONDVAR_DATA (cv));
  1452. return SCM_BOOL_T;
  1453. }
  1454. #undef FUNC_NAME
  1455. SCM_DEFINE (scm_condition_variable_p, "condition-variable?", 1, 0, 0,
  1456. (SCM obj),
  1457. "Return @code{#t} if @var{obj} is a condition variable.")
  1458. #define FUNC_NAME s_scm_condition_variable_p
  1459. {
  1460. return SCM_CONDVARP(obj) ? SCM_BOOL_T : SCM_BOOL_F;
  1461. }
  1462. #undef FUNC_NAME
  1463. /*** Select */
  1464. struct select_args
  1465. {
  1466. int nfds;
  1467. fd_set *read_fds;
  1468. fd_set *write_fds;
  1469. fd_set *except_fds;
  1470. struct timeval *timeout;
  1471. int result;
  1472. int errno_value;
  1473. };
  1474. static void *
  1475. do_std_select (void *args)
  1476. {
  1477. struct select_args *select_args;
  1478. select_args = (struct select_args *) args;
  1479. select_args->result =
  1480. select (select_args->nfds,
  1481. select_args->read_fds, select_args->write_fds,
  1482. select_args->except_fds, select_args->timeout);
  1483. select_args->errno_value = errno;
  1484. return NULL;
  1485. }
  1486. int
  1487. scm_std_select (int nfds,
  1488. fd_set *readfds,
  1489. fd_set *writefds,
  1490. fd_set *exceptfds,
  1491. struct timeval *timeout)
  1492. {
  1493. fd_set my_readfds;
  1494. int res, eno, wakeup_fd;
  1495. scm_i_thread *t = SCM_I_CURRENT_THREAD;
  1496. struct select_args args;
  1497. if (readfds == NULL)
  1498. {
  1499. FD_ZERO (&my_readfds);
  1500. readfds = &my_readfds;
  1501. }
  1502. while (scm_i_setup_sleep (t, SCM_BOOL_F, NULL, t->sleep_pipe[1]))
  1503. SCM_TICK;
  1504. wakeup_fd = t->sleep_pipe[0];
  1505. FD_SET (wakeup_fd, readfds);
  1506. if (wakeup_fd >= nfds)
  1507. nfds = wakeup_fd+1;
  1508. args.nfds = nfds;
  1509. args.read_fds = readfds;
  1510. args.write_fds = writefds;
  1511. args.except_fds = exceptfds;
  1512. args.timeout = timeout;
  1513. /* Explicitly cooperate with the GC. */
  1514. scm_without_guile (do_std_select, &args);
  1515. res = args.result;
  1516. eno = args.errno_value;
  1517. t->sleep_fd = -1;
  1518. scm_i_reset_sleep (t);
  1519. if (res > 0 && FD_ISSET (wakeup_fd, readfds))
  1520. {
  1521. char dummy;
  1522. full_read (wakeup_fd, &dummy, 1);
  1523. FD_CLR (wakeup_fd, readfds);
  1524. res -= 1;
  1525. if (res == 0)
  1526. {
  1527. eno = EINTR;
  1528. res = -1;
  1529. }
  1530. }
  1531. errno = eno;
  1532. return res;
  1533. }
  1534. /* Convenience API for blocking while in guile mode. */
  1535. #if SCM_USE_PTHREAD_THREADS
  1536. /* It seems reasonable to not run procedures related to mutex and condition
  1537. variables within `GC_do_blocking ()' since, (i) the GC can operate even
  1538. without it, and (ii) the only potential gain would be GC latency. See
  1539. http://thread.gmane.org/gmane.comp.programming.garbage-collection.boehmgc/2245/focus=2251
  1540. for a discussion of the pros and cons. */
  1541. int
  1542. scm_pthread_mutex_lock (scm_i_pthread_mutex_t *mutex)
  1543. {
  1544. int res = scm_i_pthread_mutex_lock (mutex);
  1545. return res;
  1546. }
  1547. static void
  1548. do_unlock (void *data)
  1549. {
  1550. scm_i_pthread_mutex_unlock ((scm_i_pthread_mutex_t *)data);
  1551. }
  1552. void
  1553. scm_dynwind_pthread_mutex_lock (scm_i_pthread_mutex_t *mutex)
  1554. {
  1555. scm_i_scm_pthread_mutex_lock (mutex);
  1556. scm_dynwind_unwind_handler (do_unlock, mutex, SCM_F_WIND_EXPLICITLY);
  1557. }
  1558. int
  1559. scm_pthread_cond_wait (scm_i_pthread_cond_t *cond, scm_i_pthread_mutex_t *mutex)
  1560. {
  1561. int res;
  1562. scm_i_thread *t = SCM_I_CURRENT_THREAD;
  1563. t->held_mutex = mutex;
  1564. res = scm_i_pthread_cond_wait (cond, mutex);
  1565. t->held_mutex = NULL;
  1566. return res;
  1567. }
  1568. int
  1569. scm_pthread_cond_timedwait (scm_i_pthread_cond_t *cond,
  1570. scm_i_pthread_mutex_t *mutex,
  1571. const scm_t_timespec *wt)
  1572. {
  1573. int res;
  1574. scm_i_thread *t = SCM_I_CURRENT_THREAD;
  1575. t->held_mutex = mutex;
  1576. res = scm_i_pthread_cond_timedwait (cond, mutex, wt);
  1577. t->held_mutex = NULL;
  1578. return res;
  1579. }
  1580. #endif
  1581. static void
  1582. do_unlock_with_asyncs (void *data)
  1583. {
  1584. scm_i_pthread_mutex_unlock ((scm_i_pthread_mutex_t *)data);
  1585. SCM_I_CURRENT_THREAD->block_asyncs--;
  1586. }
  1587. void
  1588. scm_i_dynwind_pthread_mutex_lock_block_asyncs (scm_i_pthread_mutex_t *mutex)
  1589. {
  1590. SCM_I_CURRENT_THREAD->block_asyncs++;
  1591. scm_i_scm_pthread_mutex_lock (mutex);
  1592. scm_dynwind_unwind_handler (do_unlock_with_asyncs, mutex,
  1593. SCM_F_WIND_EXPLICITLY);
  1594. }
  1595. unsigned long
  1596. scm_std_usleep (unsigned long usecs)
  1597. {
  1598. struct timeval tv;
  1599. tv.tv_usec = usecs % 1000000;
  1600. tv.tv_sec = usecs / 1000000;
  1601. scm_std_select (0, NULL, NULL, NULL, &tv);
  1602. return tv.tv_sec * 1000000 + tv.tv_usec;
  1603. }
  1604. unsigned int
  1605. scm_std_sleep (unsigned int secs)
  1606. {
  1607. struct timeval tv;
  1608. tv.tv_usec = 0;
  1609. tv.tv_sec = secs;
  1610. scm_std_select (0, NULL, NULL, NULL, &tv);
  1611. return tv.tv_sec;
  1612. }
  1613. /*** Misc */
  1614. SCM_DEFINE (scm_current_thread, "current-thread", 0, 0, 0,
  1615. (void),
  1616. "Return the thread that called this function.")
  1617. #define FUNC_NAME s_scm_current_thread
  1618. {
  1619. return SCM_I_CURRENT_THREAD->handle;
  1620. }
  1621. #undef FUNC_NAME
  1622. static SCM
  1623. scm_c_make_list (size_t n, SCM fill)
  1624. {
  1625. SCM res = SCM_EOL;
  1626. while (n-- > 0)
  1627. res = scm_cons (fill, res);
  1628. return res;
  1629. }
  1630. SCM_DEFINE (scm_all_threads, "all-threads", 0, 0, 0,
  1631. (void),
  1632. "Return a list of all threads.")
  1633. #define FUNC_NAME s_scm_all_threads
  1634. {
  1635. /* We can not allocate while holding the thread_admin_mutex because
  1636. of the way GC is done.
  1637. */
  1638. int n = thread_count;
  1639. scm_i_thread *t;
  1640. SCM list = scm_c_make_list (n, SCM_UNSPECIFIED), *l;
  1641. scm_i_pthread_mutex_lock (&thread_admin_mutex);
  1642. l = &list;
  1643. for (t = all_threads; t && n > 0; t = t->next_thread)
  1644. {
  1645. if (t != scm_i_signal_delivery_thread)
  1646. {
  1647. SCM_SETCAR (*l, t->handle);
  1648. l = SCM_CDRLOC (*l);
  1649. }
  1650. n--;
  1651. }
  1652. *l = SCM_EOL;
  1653. scm_i_pthread_mutex_unlock (&thread_admin_mutex);
  1654. return list;
  1655. }
  1656. #undef FUNC_NAME
  1657. SCM_DEFINE (scm_thread_exited_p, "thread-exited?", 1, 0, 0,
  1658. (SCM thread),
  1659. "Return @code{#t} iff @var{thread} has exited.\n")
  1660. #define FUNC_NAME s_scm_thread_exited_p
  1661. {
  1662. return scm_from_bool (scm_c_thread_exited_p (thread));
  1663. }
  1664. #undef FUNC_NAME
  1665. int
  1666. scm_c_thread_exited_p (SCM thread)
  1667. #define FUNC_NAME s_scm_thread_exited_p
  1668. {
  1669. scm_i_thread *t;
  1670. SCM_VALIDATE_THREAD (1, thread);
  1671. t = SCM_I_THREAD_DATA (thread);
  1672. return t->exited;
  1673. }
  1674. #undef FUNC_NAME
  1675. SCM_DEFINE (scm_total_processor_count, "total-processor-count", 0, 0, 0,
  1676. (void),
  1677. "Return the total number of processors of the machine, which\n"
  1678. "is guaranteed to be at least 1. A ``processor'' here is a\n"
  1679. "thread execution unit, which can be either:\n\n"
  1680. "@itemize\n"
  1681. "@item an execution core in a (possibly multi-core) chip, in a\n"
  1682. " (possibly multi- chip) module, in a single computer, or\n"
  1683. "@item a thread execution unit inside a core in the case of\n"
  1684. " @dfn{hyper-threaded} CPUs.\n"
  1685. "@end itemize\n\n"
  1686. "Which of the two definitions is used, is unspecified.\n")
  1687. #define FUNC_NAME s_scm_total_processor_count
  1688. {
  1689. return scm_from_ulong (num_processors (NPROC_ALL));
  1690. }
  1691. #undef FUNC_NAME
  1692. SCM_DEFINE (scm_current_processor_count, "current-processor-count", 0, 0, 0,
  1693. (void),
  1694. "Like @code{total-processor-count}, but return the number of\n"
  1695. "processors available to the current process. See\n"
  1696. "@code{setaffinity} and @code{getaffinity} for more\n"
  1697. "information.\n")
  1698. #define FUNC_NAME s_scm_current_processor_count
  1699. {
  1700. return scm_from_ulong (num_processors (NPROC_CURRENT));
  1701. }
  1702. #undef FUNC_NAME
  1703. static scm_i_pthread_cond_t wake_up_cond;
  1704. static int threads_initialized_p = 0;
  1705. /* This mutex is used by SCM_CRITICAL_SECTION_START/END.
  1706. */
  1707. scm_i_pthread_mutex_t scm_i_critical_section_mutex;
  1708. static SCM dynwind_critical_section_mutex;
  1709. void
  1710. scm_dynwind_critical_section (SCM mutex)
  1711. {
  1712. if (scm_is_false (mutex))
  1713. mutex = dynwind_critical_section_mutex;
  1714. scm_dynwind_lock_mutex (mutex);
  1715. scm_dynwind_block_asyncs ();
  1716. }
  1717. /*** Initialization */
  1718. scm_i_pthread_mutex_t scm_i_misc_mutex;
  1719. #if SCM_USE_PTHREAD_THREADS
  1720. pthread_mutexattr_t scm_i_pthread_mutexattr_recursive[1];
  1721. #endif
  1722. void
  1723. scm_threads_prehistory (void *base)
  1724. {
  1725. #if SCM_USE_PTHREAD_THREADS
  1726. pthread_mutexattr_init (scm_i_pthread_mutexattr_recursive);
  1727. pthread_mutexattr_settype (scm_i_pthread_mutexattr_recursive,
  1728. PTHREAD_MUTEX_RECURSIVE);
  1729. #endif
  1730. scm_i_pthread_mutex_init (&scm_i_critical_section_mutex,
  1731. scm_i_pthread_mutexattr_recursive);
  1732. scm_i_pthread_mutex_init (&scm_i_misc_mutex, NULL);
  1733. scm_i_pthread_cond_init (&wake_up_cond, NULL);
  1734. thread_gc_kind =
  1735. GC_new_kind (GC_new_free_list (),
  1736. GC_MAKE_PROC (GC_new_proc (thread_mark), 0),
  1737. 0, 1);
  1738. guilify_self_1 ((struct GC_stack_base *) base);
  1739. }
  1740. scm_t_bits scm_tc16_thread;
  1741. scm_t_bits scm_tc16_mutex;
  1742. scm_t_bits scm_tc16_condvar;
  1743. void
  1744. scm_init_threads ()
  1745. {
  1746. scm_tc16_thread = scm_make_smob_type ("thread", sizeof (scm_i_thread));
  1747. scm_set_smob_print (scm_tc16_thread, thread_print);
  1748. scm_tc16_mutex = scm_make_smob_type ("mutex", sizeof (fat_mutex));
  1749. scm_set_smob_print (scm_tc16_mutex, fat_mutex_print);
  1750. scm_tc16_condvar = scm_make_smob_type ("condition-variable",
  1751. sizeof (fat_cond));
  1752. scm_set_smob_print (scm_tc16_condvar, fat_cond_print);
  1753. scm_i_default_dynamic_state = SCM_BOOL_F;
  1754. guilify_self_2 (SCM_BOOL_F);
  1755. threads_initialized_p = 1;
  1756. dynwind_critical_section_mutex = scm_make_recursive_mutex ();
  1757. }
  1758. void
  1759. scm_init_threads_default_dynamic_state ()
  1760. {
  1761. SCM state = scm_make_dynamic_state (scm_current_dynamic_state ());
  1762. scm_i_default_dynamic_state = state;
  1763. }
  1764. void
  1765. scm_init_thread_procs ()
  1766. {
  1767. #include "libguile/threads.x"
  1768. }
  1769. /* IA64-specific things. */
  1770. #ifdef __ia64__
  1771. # ifdef __hpux
  1772. # include <sys/param.h>
  1773. # include <sys/pstat.h>
  1774. void *
  1775. scm_ia64_register_backing_store_base (void)
  1776. {
  1777. struct pst_vm_status vm_status;
  1778. int i = 0;
  1779. while (pstat_getprocvm (&vm_status, sizeof (vm_status), 0, i++) == 1)
  1780. if (vm_status.pst_type == PS_RSESTACK)
  1781. return (void *) vm_status.pst_vaddr;
  1782. abort ();
  1783. }
  1784. void *
  1785. scm_ia64_ar_bsp (const void *ctx)
  1786. {
  1787. uint64_t bsp;
  1788. __uc_get_ar_bsp (ctx, &bsp);
  1789. return (void *) bsp;
  1790. }
  1791. # endif /* hpux */
  1792. # ifdef linux
  1793. # include <ucontext.h>
  1794. void *
  1795. scm_ia64_register_backing_store_base (void)
  1796. {
  1797. extern void *__libc_ia64_register_backing_store_base;
  1798. return __libc_ia64_register_backing_store_base;
  1799. }
  1800. void *
  1801. scm_ia64_ar_bsp (const void *opaque)
  1802. {
  1803. const ucontext_t *ctx = opaque;
  1804. return (void *) ctx->uc_mcontext.sc_ar_bsp;
  1805. }
  1806. # endif /* linux */
  1807. # ifdef __FreeBSD__
  1808. # include <ucontext.h>
  1809. void *
  1810. scm_ia64_register_backing_store_base (void)
  1811. {
  1812. return (void *)0x8000000000000000;
  1813. }
  1814. void *
  1815. scm_ia64_ar_bsp (const void *opaque)
  1816. {
  1817. const ucontext_t *ctx = opaque;
  1818. return (void *)(ctx->uc_mcontext.mc_special.bspstore
  1819. + ctx->uc_mcontext.mc_special.ndirty);
  1820. }
  1821. # endif /* __FreeBSD__ */
  1822. #endif /* __ia64__ */
  1823. /*
  1824. Local Variables:
  1825. c-file-style: "gnu"
  1826. End:
  1827. */