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