threads.c 56 KB

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