Ruby: thread_sync.c Source File

Ruby 4.0.6p0 (2026-07-14 revision 03b6d3f8898a28604fe6cb00eae3226b821168f4)

thread_sync.c
1/* included by thread.c */
2#include "ccan/list/list.h"
3#include "builtin.h"
4
5static VALUE rb_cMutex, rb_cQueue, rb_cSizedQueue, rb_cConditionVariable;
6static VALUE rb_eClosedQueueError;
7
8/* Mutex */
9 typedef struct rb_mutex_struct {
10 rb_serial_t ec_serial;
11 rb_thread_t *th; // even if the fiber is collected, we might need access to the thread in mutex_free
12 struct rb_mutex_struct *next_mutex;
13 struct ccan_list_head waitq; /* protected by GVL */
14} rb_mutex_t;
15
16/* sync_waiter is always on-stack */
17 struct sync_waiter {
18 VALUE self;
19 rb_thread_t *th;
20 rb_fiber_t *fiber;
21 struct ccan_list_node node;
22};
23
24static inline rb_fiber_t*
25nonblocking_fiber(rb_fiber_t *fiber)
26{
27 if (rb_fiberptr_blocking(fiber)) {
28 return NULL;
29 }
30
31 return fiber;
32}
33
34 struct queue_sleep_arg {
35 VALUE self;
36 VALUE timeout;
37 rb_hrtime_t end;
38};
39
40#define MUTEX_ALLOW_TRAP FL_USER1
41
42static void
43sync_wakeup(struct ccan_list_head *head, long max)
44{
45 RUBY_DEBUG_LOG("max:%ld", max);
46
47 struct sync_waiter *cur = 0, *next;
48
49 ccan_list_for_each_safe(head, cur, next, node) {
50 ccan_list_del_init(&cur->node);
51
52 if (cur->th->status != THREAD_KILLED) {
53 if (cur->th->scheduler != Qnil && cur->fiber) {
54 rb_fiber_scheduler_unblock(cur->th->scheduler, cur->self, rb_fiberptr_self(cur->fiber));
55 }
56 else {
57 RUBY_DEBUG_LOG("target_th:%u", rb_th_serial(cur->th));
58 rb_threadptr_interrupt(cur->th);
59 cur->th->status = THREAD_RUNNABLE;
60 }
61
62 if (--max == 0) return;
63 }
64 }
65}
66
67static void
68wakeup_one(struct ccan_list_head *head)
69{
70 sync_wakeup(head, 1);
71}
72
73static void
74wakeup_all(struct ccan_list_head *head)
75{
76 sync_wakeup(head, LONG_MAX);
77}
78
79#if defined(HAVE_WORKING_FORK)
80static void rb_mutex_abandon_all(rb_mutex_t *mutexes);
81static void rb_mutex_abandon_keeping_mutexes(rb_thread_t *th);
82static void rb_mutex_abandon_locking_mutex(rb_thread_t *th);
83#endif
84static const char* rb_mutex_unlock_th(rb_mutex_t *mutex, rb_thread_t *th, rb_serial_t ec_serial);
85
86/*
87 * Document-class: Thread::Mutex
88 *
89 * Thread::Mutex implements a simple semaphore that can be used to
90 * coordinate access to shared data from multiple concurrent threads.
91 *
92 * Example:
93 *
94 * semaphore = Thread::Mutex.new
95 *
96 * a = Thread.new {
97 * semaphore.synchronize {
98 * # access shared resource
99 * }
100 * }
101 *
102 * b = Thread.new {
103 * semaphore.synchronize {
104 * # access shared resource
105 * }
106 * }
107 *
108 */
109
110static size_t
111rb_mutex_num_waiting(rb_mutex_t *mutex)
112{
113 struct sync_waiter *w = 0;
114 size_t n = 0;
115
116 ccan_list_for_each(&mutex->waitq, w, node) {
117 n++;
118 }
119
120 return n;
121}
122
123rb_thread_t* rb_fiber_threadptr(const rb_fiber_t *fiber);
124
125static bool
126mutex_locked_p(rb_mutex_t *mutex)
127{
128 return mutex->ec_serial != 0;
129}
130
131static void thread_mutex_remove(rb_thread_t *thread, rb_mutex_t *mutex);
132
133static void
134mutex_free(void *ptr)
135{
136 rb_mutex_t *mutex = ptr;
137 if (mutex_locked_p(mutex)) {
138 thread_mutex_remove(mutex->th, mutex);
139 }
140 ruby_xfree(ptr);
141}
142
143static size_t
144mutex_memsize(const void *ptr)
145{
146 return sizeof(rb_mutex_t);
147}
148
149static const rb_data_type_t mutex_data_type = {
150 "mutex",
151 {NULL, mutex_free, mutex_memsize,},
152 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
153};
154
155static rb_mutex_t *
156mutex_ptr(VALUE obj)
157{
158 rb_mutex_t *mutex;
159
160 TypedData_Get_Struct(obj, rb_mutex_t, &mutex_data_type, mutex);
161
162 return mutex;
163}
164
165 VALUE
166rb_obj_is_mutex(VALUE obj)
167{
168 return RBOOL(rb_typeddata_is_kind_of(obj, &mutex_data_type));
169}
170
171static VALUE
172mutex_alloc(VALUE klass)
173{
174 VALUE obj;
175 rb_mutex_t *mutex;
176
177 obj = TypedData_Make_Struct(klass, rb_mutex_t, &mutex_data_type, mutex);
178
179 ccan_list_head_init(&mutex->waitq);
180 return obj;
181}
182
183 VALUE
184rb_mutex_new(void)
185{
186 return mutex_alloc(rb_cMutex);
187}
188
189 VALUE
190rb_mutex_locked_p(VALUE self)
191{
192 rb_mutex_t *mutex = mutex_ptr(self);
193
194 return RBOOL(mutex_locked_p(mutex));
195}
196
197static void
198thread_mutex_insert(rb_thread_t *thread, rb_mutex_t *mutex)
199{
200 RUBY_ASSERT(!mutex->next_mutex);
201 if (thread->keeping_mutexes) {
202 mutex->next_mutex = thread->keeping_mutexes;
203 }
204
205 thread->keeping_mutexes = mutex;
206}
207
208static void
209thread_mutex_remove(rb_thread_t *thread, rb_mutex_t *mutex)
210{
211 rb_mutex_t **keeping_mutexes = &thread->keeping_mutexes;
212
213 while (*keeping_mutexes && *keeping_mutexes != mutex) {
214 // Move to the next mutex in the list:
215 keeping_mutexes = &(*keeping_mutexes)->next_mutex;
216 }
217
218 if (*keeping_mutexes) {
219 *keeping_mutexes = mutex->next_mutex;
220 mutex->next_mutex = NULL;
221 }
222}
223
224static void
225mutex_set_owner(rb_mutex_t *mutex, rb_thread_t *th, rb_serial_t ec_serial)
226{
227 mutex->th = th;
228 mutex->ec_serial = ec_serial;
229}
230
231static void
232mutex_locked(rb_mutex_t *mutex, rb_thread_t *th, rb_serial_t ec_serial)
233{
234 mutex_set_owner(mutex, th, ec_serial);
235 thread_mutex_insert(th, mutex);
236}
237
238static inline bool
239do_mutex_trylock(rb_mutex_t *mutex, rb_thread_t *th, rb_serial_t ec_serial)
240{
241 if (mutex->ec_serial == 0) {
242 RUBY_DEBUG_LOG("%p ok", mutex);
243
244 mutex_locked(mutex, th, ec_serial);
245 return true;
246 }
247 else {
248 RUBY_DEBUG_LOG("%p ng", mutex);
249 return false;
250 }
251}
252
253static VALUE
254rb_mut_trylock(rb_execution_context_t *ec, VALUE self)
255{
256 return RBOOL(do_mutex_trylock(mutex_ptr(self), ec->thread_ptr, rb_ec_serial(ec)));
257}
258
259 VALUE
260rb_mutex_trylock(VALUE self)
261{
262 return rb_mut_trylock(GET_EC(), self);
263}
264
265static VALUE
266mutex_owned_p(rb_serial_t ec_serial, rb_mutex_t *mutex)
267{
268 return RBOOL(mutex->ec_serial == ec_serial);
269}
270
271static VALUE
272call_rb_fiber_scheduler_block(VALUE mutex)
273{
274 return rb_fiber_scheduler_block(rb_fiber_scheduler_current(), mutex, Qnil);
275}
276
277static VALUE
278delete_from_waitq(VALUE value)
279{
280 struct sync_waiter *sync_waiter = (void *)value;
281 ccan_list_del(&sync_waiter->node);
282
283 return Qnil;
284}
285
286static inline rb_atomic_t threadptr_get_interrupts(rb_thread_t *th);
287
288 struct mutex_args {
289 VALUE self;
290 rb_mutex_t *mutex;
291 rb_execution_context_t *ec;
292};
293
294static inline void
295mutex_args_init(struct mutex_args *args, VALUE mutex)
296{
297 args->self = mutex;
298 args->mutex = mutex_ptr(mutex);
299 args->ec = GET_EC();
300}
301
302static VALUE
303do_mutex_lock(struct mutex_args *args, int interruptible_p)
304{
305 VALUE self = args->self;
306 rb_execution_context_t *ec = args->ec;
307 rb_thread_t *th = ec->thread_ptr;
308 rb_fiber_t *fiber = ec->fiber_ptr;
309 rb_serial_t ec_serial = rb_ec_serial(ec);
310 rb_mutex_t *mutex = args->mutex;
311 rb_atomic_t saved_ints = 0;
312
313 /* When running trap handler */
314 if (!FL_TEST_RAW(self, MUTEX_ALLOW_TRAP) &&
315 th->ec->interrupt_mask & TRAP_INTERRUPT_MASK) {
316 rb_raise(rb_eThreadError, "can't be called from trap context");
317 }
318
319 if (!do_mutex_trylock(mutex, th, ec_serial)) {
320 if (mutex->ec_serial == ec_serial) {
321 rb_raise(rb_eThreadError, "deadlock; recursive locking");
322 }
323
324 while (mutex->ec_serial != ec_serial) {
325 VM_ASSERT(mutex->ec_serial != 0);
326
327 VALUE scheduler = rb_fiber_scheduler_current();
328 if (scheduler != Qnil) {
329 struct sync_waiter sync_waiter = {
330 .self = self,
331 .th = th,
332 .fiber = nonblocking_fiber(fiber)
333 };
334
335 ccan_list_add_tail(&mutex->waitq, &sync_waiter.node);
336
337 rb_ensure(call_rb_fiber_scheduler_block, self, delete_from_waitq, (VALUE)&sync_waiter);
338
339 if (!mutex->ec_serial) {
340 mutex_set_owner(mutex, th, ec_serial);
341 }
342 }
343 else {
344 if (!th->vm->thread_ignore_deadlock && mutex->th == th) {
345 rb_raise(rb_eThreadError, "deadlock; lock already owned by another fiber belonging to the same thread");
346 }
347
348 struct sync_waiter sync_waiter = {
349 .self = self,
350 .th = th,
351 .fiber = nonblocking_fiber(fiber),
352 };
353
354 RUBY_DEBUG_LOG("%p wait", mutex);
355
356 // similar code with `sleep_forever`, but
357 // sleep_forever(SLEEP_DEADLOCKABLE) raises an exception.
358 // Ensure clause is needed like but `rb_ensure` a bit slow.
359 //
360 // begin
361 // sleep_forever(th, SLEEP_DEADLOCKABLE);
362 // ensure
363 // ccan_list_del(&sync_waiter.node);
364 // end
365 enum rb_thread_status prev_status = th->status;
366 th->status = THREAD_STOPPED_FOREVER;
367 rb_ractor_sleeper_threads_inc(th->ractor);
368 rb_check_deadlock(th->ractor);
369
370 RUBY_ASSERT(!th->locking_mutex);
371 th->locking_mutex = self;
372
373 ccan_list_add_tail(&mutex->waitq, &sync_waiter.node);
374 {
375 native_sleep(th, NULL);
376 }
377 ccan_list_del(&sync_waiter.node);
378
379 // unlocked by another thread while sleeping
380 if (!mutex->ec_serial) {
381 mutex_set_owner(mutex, th, ec_serial);
382 }
383
384 rb_ractor_sleeper_threads_dec(th->ractor);
385 th->status = prev_status;
386 th->locking_mutex = Qfalse;
387
388 RUBY_DEBUG_LOG("%p wakeup", mutex);
389 }
390
391 if (interruptible_p) {
392 /* release mutex before checking for interrupts...as interrupt checking
393 * code might call rb_raise() */
394 if (mutex->ec_serial == ec_serial) {
395 mutex->th = NULL;
396 mutex->ec_serial = 0;
397 }
398 RUBY_VM_CHECK_INTS_BLOCKING(th->ec); /* may release mutex */
399 if (!mutex->ec_serial) {
400 mutex_set_owner(mutex, th, ec_serial);
401 }
402 }
403 else {
404 // clear interrupt information
405 if (RUBY_VM_INTERRUPTED(th->ec)) {
406 // reset interrupts
407 if (saved_ints == 0) {
408 saved_ints = threadptr_get_interrupts(th);
409 }
410 else {
411 // ignore additional interrupts
412 threadptr_get_interrupts(th);
413 }
414 }
415 }
416 }
417
418 if (saved_ints) th->ec->interrupt_flag = saved_ints;
419 if (mutex->ec_serial == ec_serial) mutex_locked(mutex, th, ec_serial);
420 }
421
422 RUBY_DEBUG_LOG("%p locked", mutex);
423
424 // assertion
425 if (mutex_owned_p(ec_serial, mutex) == Qfalse) rb_bug("do_mutex_lock: mutex is not owned.");
426
427 return self;
428}
429
430static VALUE
431mutex_lock_uninterruptible(VALUE self)
432{
433 struct mutex_args args;
434 mutex_args_init(&args, self);
435 return do_mutex_lock(&args, 0);
436}
437
438static VALUE
439rb_mut_lock(rb_execution_context_t *ec, VALUE self)
440{
441 struct mutex_args args = {
442 .self = self,
443 .mutex = mutex_ptr(self),
444 .ec = ec,
445 };
446 return do_mutex_lock(&args, 1);
447}
448
449 VALUE
450rb_mutex_lock(VALUE self)
451{
452 struct mutex_args args;
453 mutex_args_init(&args, self);
454 return do_mutex_lock(&args, 1);
455}
456
457static VALUE
458rb_mut_owned_p(rb_execution_context_t *ec, VALUE self)
459{
460 return mutex_owned_p(rb_ec_serial(ec), mutex_ptr(self));
461}
462
463 VALUE
464rb_mutex_owned_p(VALUE self)
465{
466 return rb_mut_owned_p(GET_EC(), self);
467}
468
469static const char *
470rb_mutex_unlock_th(rb_mutex_t *mutex, rb_thread_t *th, rb_serial_t ec_serial)
471{
472 RUBY_DEBUG_LOG("%p", mutex);
473
474 if (mutex->ec_serial == 0) {
475 return "Attempt to unlock a mutex which is not locked";
476 }
477 else if (ec_serial && mutex->ec_serial != ec_serial) {
478 return "Attempt to unlock a mutex which is locked by another thread/fiber";
479 }
480
481 struct sync_waiter *cur = 0, *next;
482
483 mutex->ec_serial = 0;
484 thread_mutex_remove(th, mutex);
485
486 ccan_list_for_each_safe(&mutex->waitq, cur, next, node) {
487 ccan_list_del_init(&cur->node);
488
489 if (cur->th->scheduler != Qnil && cur->fiber) {
490 rb_fiber_scheduler_unblock(cur->th->scheduler, cur->self, rb_fiberptr_self(cur->fiber));
491 return NULL;
492 }
493 else {
494 switch (cur->th->status) {
495 case THREAD_RUNNABLE: /* from someone else calling Thread#run */
496 case THREAD_STOPPED_FOREVER: /* likely (rb_mutex_lock) */
497 RUBY_DEBUG_LOG("wakeup th:%u", rb_th_serial(cur->th));
498 rb_threadptr_interrupt(cur->th);
499 return NULL;
500 case THREAD_STOPPED: /* probably impossible */
501 rb_bug("unexpected THREAD_STOPPED");
502 case THREAD_KILLED:
503 /* not sure about this, possible in exit GC? */
504 rb_bug("unexpected THREAD_KILLED");
505 continue;
506 }
507 }
508 }
509
510 // We did not find any threads to wake up, so we can just return with no error:
511 return NULL;
512}
513
514static void
515do_mutex_unlock(struct mutex_args *args)
516{
517 const char *err;
518 rb_mutex_t *mutex = args->mutex;
519 rb_thread_t *th = rb_ec_thread_ptr(args->ec);
520
521 err = rb_mutex_unlock_th(mutex, th, rb_ec_serial(args->ec));
522 if (err) rb_raise(rb_eThreadError, "%s", err);
523}
524
525static VALUE
526do_mutex_unlock_safe(VALUE args)
527{
528 do_mutex_unlock((struct mutex_args *)args);
529 return Qnil;
530}
531
532 VALUE
533rb_mutex_unlock(VALUE self)
534{
535 struct mutex_args args;
536 mutex_args_init(&args, self);
537 do_mutex_unlock(&args);
538 return self;
539}
540
541static VALUE
542rb_mut_unlock(rb_execution_context_t *ec, VALUE self)
543{
544 struct mutex_args args = {
545 .self = self,
546 .mutex = mutex_ptr(self),
547 .ec = ec,
548 };
549 do_mutex_unlock(&args);
550 return self;
551}
552
553#if defined(HAVE_WORKING_FORK)
554static void
555rb_mutex_abandon_keeping_mutexes(rb_thread_t *th)
556{
557 rb_mutex_abandon_all(th->keeping_mutexes);
558 th->keeping_mutexes = NULL;
559}
560
561static void
562rb_mutex_abandon_locking_mutex(rb_thread_t *th)
563{
564 if (th->locking_mutex) {
565 rb_mutex_t *mutex = mutex_ptr(th->locking_mutex);
566
567 ccan_list_head_init(&mutex->waitq);
568 th->locking_mutex = Qfalse;
569 }
570}
571
572static void
573rb_mutex_abandon_all(rb_mutex_t *mutexes)
574{
575 rb_mutex_t *mutex;
576
577 while (mutexes) {
578 mutex = mutexes;
579 mutexes = mutex->next_mutex;
580 mutex->ec_serial = 0;
581 mutex->next_mutex = 0;
582 ccan_list_head_init(&mutex->waitq);
583 }
584}
585#endif
586
587 struct rb_mutex_sleep_arguments {
588 VALUE self;
589 VALUE timeout;
590};
591
592static VALUE
593mutex_sleep_begin(VALUE _arguments)
594{
595 struct rb_mutex_sleep_arguments *arguments = (struct rb_mutex_sleep_arguments *)_arguments;
596 VALUE timeout = arguments->timeout;
597 VALUE woken = Qtrue;
598
599 VALUE scheduler = rb_fiber_scheduler_current();
600 if (scheduler != Qnil) {
601 rb_fiber_scheduler_kernel_sleep(scheduler, timeout);
602 }
603 else {
604 if (NIL_P(timeout)) {
605 rb_thread_sleep_deadly_allow_spurious_wakeup(arguments->self, Qnil, 0);
606 }
607 else {
608 struct timeval timeout_value = rb_time_interval(timeout);
609 rb_hrtime_t relative_timeout = rb_timeval2hrtime(&timeout_value);
610 /* permit spurious check */
611 woken = RBOOL(sleep_hrtime(GET_THREAD(), relative_timeout, 0));
612 }
613 }
614
615 return woken;
616}
617
618static VALUE
619rb_mut_sleep(rb_execution_context_t *ec, VALUE self, VALUE timeout)
620{
621 if (!NIL_P(timeout)) {
622 // Validate the argument:
623 rb_time_interval(timeout);
624 }
625
626 rb_mut_unlock(ec, self);
627 time_t beg = time(0);
628
629 struct rb_mutex_sleep_arguments arguments = {
630 .self = self,
631 .timeout = timeout,
632 };
633
634 VALUE woken = rb_ec_ensure(ec, mutex_sleep_begin, (VALUE)&arguments, mutex_lock_uninterruptible, self);
635
636 RUBY_VM_CHECK_INTS_BLOCKING(ec);
637 if (!woken) return Qnil;
638 time_t end = time(0) - beg;
639 return TIMET2NUM(end);
640}
641
642 VALUE
643rb_mutex_sleep(VALUE self, VALUE timeout)
644{
645 return rb_mut_sleep(GET_EC(), self, timeout);
646}
647
648 VALUE
649rb_mutex_synchronize(VALUE self, VALUE (*func)(VALUE arg), VALUE arg)
650{
651 struct mutex_args args;
652 mutex_args_init(&args, self);
653 do_mutex_lock(&args, 1);
654 return rb_ec_ensure(args.ec, func, arg, do_mutex_unlock_safe, (VALUE)&args);
655}
656
657static VALUE
658do_ec_yield(VALUE _ec)
659{
660 return rb_ec_yield((rb_execution_context_t *)_ec, Qundef);
661}
662
663 VALUE
664rb_mut_synchronize(rb_execution_context_t *ec, VALUE self)
665{
666 struct mutex_args args = {
667 .self = self,
668 .mutex = mutex_ptr(self),
669 .ec = ec,
670 };
671 do_mutex_lock(&args, 1);
672 return rb_ec_ensure(args.ec, do_ec_yield, (VALUE)ec, do_mutex_unlock_safe, (VALUE)&args);
673}
674
675void
676rb_mutex_allow_trap(VALUE self, int val)
677{
678 Check_TypedStruct(self, &mutex_data_type);
679
680 if (val)
681 FL_SET_RAW(self, MUTEX_ALLOW_TRAP);
682 else
683 FL_UNSET_RAW(self, MUTEX_ALLOW_TRAP);
684}
685
686/* Queue */
687
688#define queue_waitq(q) UNALIGNED_MEMBER_PTR(q, waitq)
689#define queue_list(q) UNALIGNED_MEMBER_PTR(q, que)
690RBIMPL_ATTR_PACKED_STRUCT_UNALIGNED_BEGIN()
691struct rb_queue {
692 struct ccan_list_head waitq;
693 rb_serial_t fork_gen;
694 const VALUE que;
695 int num_waiting;
696} RBIMPL_ATTR_PACKED_STRUCT_UNALIGNED_END();
697
698#define szqueue_waitq(sq) UNALIGNED_MEMBER_PTR(sq, q.waitq)
699#define szqueue_list(sq) UNALIGNED_MEMBER_PTR(sq, q.que)
700#define szqueue_pushq(sq) UNALIGNED_MEMBER_PTR(sq, pushq)
701RBIMPL_ATTR_PACKED_STRUCT_UNALIGNED_BEGIN()
702struct rb_szqueue {
703 struct rb_queue q;
704 int num_waiting_push;
705 struct ccan_list_head pushq;
706 long max;
707} RBIMPL_ATTR_PACKED_STRUCT_UNALIGNED_END();
708
709static void
710queue_mark_and_move(void *ptr)
711{
712 struct rb_queue *q = ptr;
713
714 /* no need to mark threads in waitq, they are on stack */
715 rb_gc_mark_and_move((VALUE *)UNALIGNED_MEMBER_PTR(q, que));
716}
717
718static size_t
719queue_memsize(const void *ptr)
720{
721 return sizeof(struct rb_queue);
722}
723
724static const rb_data_type_t queue_data_type = {
725 .wrap_struct_name = "Thread::Queue",
726 .function = {
727 .dmark = queue_mark_and_move,
728 .dfree = RUBY_TYPED_DEFAULT_FREE,
729 .dsize = queue_memsize,
730 .dcompact = queue_mark_and_move,
731 },
732 .flags = RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED,
733};
734
735static VALUE
736queue_alloc(VALUE klass)
737{
738 VALUE obj;
739 struct rb_queue *q;
740
741 obj = TypedData_Make_Struct(klass, struct rb_queue, &queue_data_type, q);
742 ccan_list_head_init(queue_waitq(q));
743 return obj;
744}
745
746static int
747queue_fork_check(struct rb_queue *q)
748{
749 rb_serial_t fork_gen = GET_VM()->fork_gen;
750
751 if (q->fork_gen == fork_gen) {
752 return 0;
753 }
754 /* forked children can't reach into parent thread stacks */
755 q->fork_gen = fork_gen;
756 ccan_list_head_init(queue_waitq(q));
757 q->num_waiting = 0;
758 return 1;
759}
760
761static struct rb_queue *
762queue_ptr(VALUE obj)
763{
764 struct rb_queue *q;
765
766 TypedData_Get_Struct(obj, struct rb_queue, &queue_data_type, q);
767 queue_fork_check(q);
768
769 return q;
770}
771
772#define QUEUE_CLOSED FL_USER5
773
774static rb_hrtime_t
775queue_timeout2hrtime(VALUE timeout)
776{
777 if (NIL_P(timeout)) {
778 return (rb_hrtime_t)0;
779 }
780 rb_hrtime_t rel = 0;
781 if (FIXNUM_P(timeout)) {
782 rel = rb_sec2hrtime(NUM2TIMET(timeout));
783 }
784 else {
785 double2hrtime(&rel, rb_num2dbl(timeout));
786 }
787 return rb_hrtime_add(rel, rb_hrtime_now());
788}
789
790static void
791szqueue_mark_and_move(void *ptr)
792{
793 struct rb_szqueue *sq = ptr;
794
795 queue_mark_and_move(&sq->q);
796}
797
798static size_t
799szqueue_memsize(const void *ptr)
800{
801 return sizeof(struct rb_szqueue);
802}
803
804static const rb_data_type_t szqueue_data_type = {
805 .wrap_struct_name = "Thread::SizedQueue",
806 .function = {
807 .dmark = szqueue_mark_and_move,
808 .dfree = RUBY_TYPED_DEFAULT_FREE,
809 .dsize = szqueue_memsize,
810 .dcompact = szqueue_mark_and_move,
811 },
812 .parent = &queue_data_type,
813 .flags = RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED,
814};
815
816static VALUE
817szqueue_alloc(VALUE klass)
818{
819 struct rb_szqueue *sq;
820 VALUE obj = TypedData_Make_Struct(klass, struct rb_szqueue,
821 &szqueue_data_type, sq);
822 ccan_list_head_init(szqueue_waitq(sq));
823 ccan_list_head_init(szqueue_pushq(sq));
824 return obj;
825}
826
827static struct rb_szqueue *
828szqueue_ptr(VALUE obj)
829{
830 struct rb_szqueue *sq;
831
832 TypedData_Get_Struct(obj, struct rb_szqueue, &szqueue_data_type, sq);
833 if (queue_fork_check(&sq->q)) {
834 ccan_list_head_init(szqueue_pushq(sq));
835 sq->num_waiting_push = 0;
836 }
837
838 return sq;
839}
840
841static VALUE
842ary_buf_new(void)
843{
844 return rb_ary_hidden_new(1);
845}
846
847static inline VALUE
848check_array(VALUE obj, VALUE ary)
849{
850 if (RB_LIKELY(ary)) {
851 return ary;
852 }
853 rb_raise(rb_eTypeError, "%+"PRIsVALUE" not initialized", obj);
854}
855
856static long
857queue_length(VALUE self, struct rb_queue *q)
858{
859 return RARRAY_LEN(check_array(self, q->que));
860}
861
862static int
863queue_closed_p(VALUE self)
864{
865 return FL_TEST_RAW(self, QUEUE_CLOSED) != 0;
866}
867
868/*
869 * Document-class: ClosedQueueError
870 *
871 * The exception class which will be raised when pushing into a closed
872 * Queue. See Thread::Queue#close and Thread::SizedQueue#close.
873 */
874
875NORETURN(static void raise_closed_queue_error(VALUE self));
876
877static void
878raise_closed_queue_error(VALUE self)
879{
880 rb_raise(rb_eClosedQueueError, "queue closed");
881}
882
883static VALUE
884queue_closed_result(VALUE self, struct rb_queue *q)
885{
886 RUBY_ASSERT(queue_length(self, q) == 0);
887 return Qnil;
888}
889
890/*
891 * Document-class: Thread::Queue
892 *
893 * The Thread::Queue class implements multi-producer, multi-consumer
894 * queues. It is especially useful in threaded programming when
895 * information must be exchanged safely between multiple threads. The
896 * Thread::Queue class implements all the required locking semantics.
897 *
898 * The class implements FIFO (first in, first out) type of queue.
899 * In a FIFO queue, the first tasks added are the first retrieved.
900 *
901 * Example:
902 *
903 * queue = Thread::Queue.new
904 *
905 * producer = Thread.new do
906 * 5.times do |i|
907 * sleep rand(i) # simulate expense
908 * queue << i
909 * puts "#{i} produced"
910 * end
911 * end
912 *
913 * consumer = Thread.new do
914 * 5.times do |i|
915 * value = queue.pop
916 * sleep rand(i/2) # simulate expense
917 * puts "consumed #{value}"
918 * end
919 * end
920 *
921 * consumer.join
922 *
923 */
924
925/*
926 * Document-method: Queue::new
927 *
928 * call-seq:
929 * Thread::Queue.new -> empty_queue
930 * Thread::Queue.new(enumerable) -> queue
931 *
932 * Creates a new queue instance, optionally using the contents of an +enumerable+
933 * for its initial state.
934 *
935 * Example:
936 *
937 * q = Thread::Queue.new
938 * #=> #<Thread::Queue:0x00007ff7501110d0>
939 * q.empty?
940 * #=> true
941 *
942 * q = Thread::Queue.new([1, 2, 3])
943 * #=> #<Thread::Queue:0x00007ff7500ec500>
944 * q.empty?
945 * #=> false
946 * q.pop
947 * #=> 1
948 */
949
950static VALUE
951rb_queue_initialize(int argc, VALUE *argv, VALUE self)
952{
953 VALUE initial;
954 struct rb_queue *q = queue_ptr(self);
955 if ((argc = rb_scan_args(argc, argv, "01", &initial)) == 1) {
956 initial = rb_to_array(initial);
957 }
958 RB_OBJ_WRITE(self, queue_list(q), ary_buf_new());
959 ccan_list_head_init(queue_waitq(q));
960 if (argc == 1) {
961 rb_ary_concat(q->que, initial);
962 }
963 return self;
964}
965
966static VALUE
967queue_do_push(VALUE self, struct rb_queue *q, VALUE obj)
968{
969 if (queue_closed_p(self)) {
970 raise_closed_queue_error(self);
971 }
972 rb_ary_push(check_array(self, q->que), obj);
973 wakeup_one(queue_waitq(q));
974 return self;
975}
976
977/*
978 * Document-method: Thread::Queue#close
979 * call-seq:
980 * close
981 *
982 * Closes the queue. A closed queue cannot be re-opened.
983 *
984 * After the call to close completes, the following are true:
985 *
986 * - +closed?+ will return true
987 *
988 * - +close+ will be ignored.
989 *
990 * - calling enq/push/<< will raise a +ClosedQueueError+.
991 *
992 * - when +empty?+ is false, calling deq/pop/shift will return an object
993 * from the queue as usual.
994 * - when +empty?+ is true, deq(false) will not suspend the thread and will return nil.
995 * deq(true) will raise a +ThreadError+.
996 *
997 * ClosedQueueError is inherited from StopIteration, so that you can break loop block.
998 *
999 * Example:
1000 *
1001 * q = Thread::Queue.new
1002 * Thread.new{
1003 * while e = q.deq # wait for nil to break loop
1004 * # ...
1005 * end
1006 * }
1007 * q.close
1008 */
1009
1010static VALUE
1011rb_queue_close(VALUE self)
1012{
1013 struct rb_queue *q = queue_ptr(self);
1014
1015 if (!queue_closed_p(self)) {
1016 FL_SET(self, QUEUE_CLOSED);
1017
1018 wakeup_all(queue_waitq(q));
1019 }
1020
1021 return self;
1022}
1023
1024/*
1025 * Document-method: Thread::Queue#closed?
1026 * call-seq: closed?
1027 *
1028 * Returns +true+ if the queue is closed.
1029 */
1030
1031static VALUE
1032rb_queue_closed_p(VALUE self)
1033{
1034 return RBOOL(queue_closed_p(self));
1035}
1036
1037/*
1038 * Document-method: Thread::Queue#push
1039 * call-seq:
1040 * push(object)
1041 * enq(object)
1042 * <<(object)
1043 *
1044 * Pushes the given +object+ to the queue.
1045 */
1046
1047static VALUE
1048rb_queue_push(VALUE self, VALUE obj)
1049{
1050 return queue_do_push(self, queue_ptr(self), obj);
1051}
1052
1053static VALUE
1054queue_sleep(VALUE _args)
1055{
1056 struct queue_sleep_arg *args = (struct queue_sleep_arg *)_args;
1057 rb_thread_sleep_deadly_allow_spurious_wakeup(args->self, args->timeout, args->end);
1058 return Qnil;
1059}
1060
1061 struct queue_waiter {
1062 struct sync_waiter w;
1063 union {
1064 struct rb_queue *q;
1065 struct rb_szqueue *sq;
1066 } as;
1067};
1068
1069static VALUE
1070queue_sleep_done(VALUE p)
1071{
1072 struct queue_waiter *qw = (struct queue_waiter *)p;
1073
1074 ccan_list_del(&qw->w.node);
1075 qw->as.q->num_waiting--;
1076
1077 return Qfalse;
1078}
1079
1080static VALUE
1081szqueue_sleep_done(VALUE p)
1082{
1083 struct queue_waiter *qw = (struct queue_waiter *)p;
1084
1085 ccan_list_del(&qw->w.node);
1086 qw->as.sq->num_waiting_push--;
1087
1088 return Qfalse;
1089}
1090
1091static inline VALUE
1092queue_do_pop(rb_execution_context_t *ec, VALUE self, struct rb_queue *q, VALUE non_block, VALUE timeout)
1093{
1094 check_array(self, q->que);
1095 if (RARRAY_LEN(q->que) == 0) {
1096 if (RTEST(non_block)) {
1097 rb_raise(rb_eThreadError, "queue empty");
1098 }
1099
1100 if (RTEST(rb_equal(INT2FIX(0), timeout))) {
1101 return Qnil;
1102 }
1103 }
1104
1105 rb_hrtime_t end = queue_timeout2hrtime(timeout);
1106 while (RARRAY_LEN(q->que) == 0) {
1107 if (queue_closed_p(self)) {
1108 return queue_closed_result(self, q);
1109 }
1110 else {
1111 RUBY_ASSERT(RARRAY_LEN(q->que) == 0);
1112 RUBY_ASSERT(queue_closed_p(self) == 0);
1113
1114 struct queue_waiter queue_waiter = {
1115 .w = {.self = self, .th = ec->thread_ptr, .fiber = nonblocking_fiber(ec->fiber_ptr)},
1116 .as = {.q = q}
1117 };
1118
1119 struct ccan_list_head *waitq = queue_waitq(q);
1120
1121 ccan_list_add_tail(waitq, &queue_waiter.w.node);
1122 queue_waiter.as.q->num_waiting++;
1123
1124 struct queue_sleep_arg queue_sleep_arg = {
1125 .self = self,
1126 .timeout = timeout,
1127 .end = end
1128 };
1129
1130 rb_ensure(queue_sleep, (VALUE)&queue_sleep_arg, queue_sleep_done, (VALUE)&queue_waiter);
1131 if (!NIL_P(timeout) && (rb_hrtime_now() >= end))
1132 break;
1133 }
1134 }
1135
1136 return rb_ary_shift(q->que);
1137}
1138
1139static VALUE
1140rb_queue_pop(rb_execution_context_t *ec, VALUE self, VALUE non_block, VALUE timeout)
1141{
1142 return queue_do_pop(ec, self, queue_ptr(self), non_block, timeout);
1143}
1144
1145/*
1146 * Document-method: Thread::Queue#empty?
1147 * call-seq: empty?
1148 *
1149 * Returns +true+ if the queue is empty.
1150 */
1151
1152static VALUE
1153rb_queue_empty_p(VALUE self)
1154{
1155 return RBOOL(queue_length(self, queue_ptr(self)) == 0);
1156}
1157
1158/*
1159 * Document-method: Thread::Queue#clear
1160 *
1161 * Removes all objects from the queue.
1162 */
1163
1164static VALUE
1165rb_queue_clear(VALUE self)
1166{
1167 struct rb_queue *q = queue_ptr(self);
1168
1169 rb_ary_clear(check_array(self, q->que));
1170 return self;
1171}
1172
1173/*
1174 * Document-method: Thread::Queue#length
1175 * call-seq:
1176 * length
1177 * size
1178 *
1179 * Returns the length of the queue.
1180 */
1181
1182static VALUE
1183rb_queue_length(VALUE self)
1184{
1185 return LONG2NUM(queue_length(self, queue_ptr(self)));
1186}
1187
1188NORETURN(static VALUE rb_queue_freeze(VALUE self));
1189/*
1190 * call-seq:
1191 * freeze
1192 *
1193 * The queue can't be frozen, so this method raises an exception:
1194 * Thread::Queue.new.freeze # Raises TypeError (cannot freeze #<Thread::Queue:0x...>)
1195 *
1196 */
1197static VALUE
1198rb_queue_freeze(VALUE self)
1199{
1200 rb_raise(rb_eTypeError, "cannot freeze " "%+"PRIsVALUE, self);
1201 UNREACHABLE_RETURN(self);
1202}
1203
1204/*
1205 * Document-method: Thread::Queue#num_waiting
1206 *
1207 * Returns the number of threads waiting on the queue.
1208 */
1209
1210static VALUE
1211rb_queue_num_waiting(VALUE self)
1212{
1213 struct rb_queue *q = queue_ptr(self);
1214
1215 return INT2NUM(q->num_waiting);
1216}
1217
1218/*
1219 * Document-class: Thread::SizedQueue
1220 *
1221 * This class represents queues of specified size capacity. The push operation
1222 * may be blocked if the capacity is full.
1223 *
1224 * See Thread::Queue for an example of how a Thread::SizedQueue works.
1225 */
1226
1227/*
1228 * Document-method: SizedQueue::new
1229 * call-seq: new(max)
1230 *
1231 * Creates a fixed-length queue with a maximum size of +max+.
1232 */
1233
1234static VALUE
1235rb_szqueue_initialize(VALUE self, VALUE vmax)
1236{
1237 long max;
1238 struct rb_szqueue *sq = szqueue_ptr(self);
1239
1240 max = NUM2LONG(vmax);
1241 if (max <= 0) {
1242 rb_raise(rb_eArgError, "queue size must be positive");
1243 }
1244
1245 RB_OBJ_WRITE(self, szqueue_list(sq), ary_buf_new());
1246 ccan_list_head_init(szqueue_waitq(sq));
1247 ccan_list_head_init(szqueue_pushq(sq));
1248 sq->max = max;
1249
1250 return self;
1251}
1252
1253/*
1254 * Document-method: Thread::SizedQueue#close
1255 * call-seq:
1256 * close
1257 *
1258 * Similar to Thread::Queue#close.
1259 *
1260 * The difference is behavior with waiting enqueuing threads.
1261 *
1262 * If there are waiting enqueuing threads, they are interrupted by
1263 * raising ClosedQueueError('queue closed').
1264 */
1265static VALUE
1266rb_szqueue_close(VALUE self)
1267{
1268 if (!queue_closed_p(self)) {
1269 struct rb_szqueue *sq = szqueue_ptr(self);
1270
1271 FL_SET(self, QUEUE_CLOSED);
1272 wakeup_all(szqueue_waitq(sq));
1273 wakeup_all(szqueue_pushq(sq));
1274 }
1275 return self;
1276}
1277
1278/*
1279 * Document-method: Thread::SizedQueue#max
1280 *
1281 * Returns the maximum size of the queue.
1282 */
1283
1284static VALUE
1285rb_szqueue_max_get(VALUE self)
1286{
1287 return LONG2NUM(szqueue_ptr(self)->max);
1288}
1289
1290/*
1291 * Document-method: Thread::SizedQueue#max=
1292 * call-seq: max=(number)
1293 *
1294 * Sets the maximum size of the queue to the given +number+.
1295 */
1296
1297static VALUE
1298rb_szqueue_max_set(VALUE self, VALUE vmax)
1299{
1300 long max = NUM2LONG(vmax);
1301 long diff = 0;
1302 struct rb_szqueue *sq = szqueue_ptr(self);
1303
1304 if (max <= 0) {
1305 rb_raise(rb_eArgError, "queue size must be positive");
1306 }
1307 if (max > sq->max) {
1308 diff = max - sq->max;
1309 }
1310 sq->max = max;
1311 sync_wakeup(szqueue_pushq(sq), diff);
1312 return vmax;
1313}
1314
1315static VALUE
1316rb_szqueue_push(rb_execution_context_t *ec, VALUE self, VALUE object, VALUE non_block, VALUE timeout)
1317{
1318 struct rb_szqueue *sq = szqueue_ptr(self);
1319
1320 if (queue_length(self, &sq->q) >= sq->max) {
1321 if (RTEST(non_block)) {
1322 rb_raise(rb_eThreadError, "queue full");
1323 }
1324
1325 if (RTEST(rb_equal(INT2FIX(0), timeout))) {
1326 return Qnil;
1327 }
1328 }
1329
1330 rb_hrtime_t end = queue_timeout2hrtime(timeout);
1331 while (queue_length(self, &sq->q) >= sq->max) {
1332 if (queue_closed_p(self)) {
1333 raise_closed_queue_error(self);
1334 }
1335 else {
1336 struct queue_waiter queue_waiter = {
1337 .w = {.self = self, .th = ec->thread_ptr, .fiber = nonblocking_fiber(ec->fiber_ptr)},
1338 .as = {.sq = sq}
1339 };
1340
1341 struct ccan_list_head *pushq = szqueue_pushq(sq);
1342
1343 ccan_list_add_tail(pushq, &queue_waiter.w.node);
1344 sq->num_waiting_push++;
1345
1346 struct queue_sleep_arg queue_sleep_arg = {
1347 .self = self,
1348 .timeout = timeout,
1349 .end = end
1350 };
1351 rb_ensure(queue_sleep, (VALUE)&queue_sleep_arg, szqueue_sleep_done, (VALUE)&queue_waiter);
1352 if (!NIL_P(timeout) && rb_hrtime_now() >= end) {
1353 return Qnil;
1354 }
1355 }
1356 }
1357
1358 return queue_do_push(self, &sq->q, object);
1359}
1360
1361static VALUE
1362rb_szqueue_pop(rb_execution_context_t *ec, VALUE self, VALUE non_block, VALUE timeout)
1363{
1364 struct rb_szqueue *sq = szqueue_ptr(self);
1365 VALUE retval = queue_do_pop(ec, self, &sq->q, non_block, timeout);
1366
1367 if (queue_length(self, &sq->q) < sq->max) {
1368 wakeup_one(szqueue_pushq(sq));
1369 }
1370
1371 return retval;
1372}
1373
1374/*
1375 * Document-method: Thread::SizedQueue#clear
1376 *
1377 * Removes all objects from the queue.
1378 */
1379
1380static VALUE
1381rb_szqueue_clear(VALUE self)
1382{
1383 struct rb_szqueue *sq = szqueue_ptr(self);
1384
1385 rb_ary_clear(check_array(self, sq->q.que));
1386 wakeup_all(szqueue_pushq(sq));
1387 return self;
1388}
1389
1390/*
1391 * Document-method: Thread::SizedQueue#num_waiting
1392 *
1393 * Returns the number of threads waiting on the queue.
1394 */
1395
1396static VALUE
1397rb_szqueue_num_waiting(VALUE self)
1398{
1399 struct rb_szqueue *sq = szqueue_ptr(self);
1400
1401 return INT2NUM(sq->q.num_waiting + sq->num_waiting_push);
1402}
1403
1404
1405/* ConditionalVariable */
1406 struct rb_condvar {
1407 struct ccan_list_head waitq;
1408 rb_serial_t fork_gen;
1409};
1410
1411/*
1412 * Document-class: Thread::ConditionVariable
1413 *
1414 * ConditionVariable objects augment class Mutex. Using condition variables,
1415 * it is possible to suspend while in the middle of a critical section until a
1416 * condition is met, such as a resource becomes available.
1417 *
1418 * Due to non-deterministic scheduling and spurious wake-ups, users of
1419 * condition variables should always use a separate boolean predicate (such as
1420 * reading from a boolean variable) to check if the condition is actually met
1421 * before starting to wait, and should wait in a loop, re-checking the
1422 * condition every time the ConditionVariable is waken up. The idiomatic way
1423 * of using condition variables is calling the +wait+ method in an +until+
1424 * loop with the predicate as the loop condition.
1425 *
1426 * condvar.wait(mutex) until condition_is_met
1427 *
1428 * In the example below, we use the boolean variable +resource_available+
1429 * (which is protected by +mutex+) to indicate the availability of the
1430 * resource, and use +condvar+ to wait for that variable to become true. Note
1431 * that:
1432 *
1433 * 1. Thread +b+ may be scheduled before thread +a1+ and +a2+, and may run so
1434 * fast that it have already made the resource available before either
1435 * +a1+ or +a2+ starts. Therefore, +a1+ and +a2+ should check if
1436 * +resource_available+ is already true before starting to wait.
1437 * 2. The +wait+ method may spuriously wake up without signalling. Therefore,
1438 * thread +a1+ and +a2+ should recheck +resource_available+ after the
1439 * +wait+ method returns, and go back to wait if the condition is not
1440 * actually met.
1441 * 3. It is possible that thread +a2+ starts right after thread +a1+ is waken
1442 * up by +b+. Thread +a2+ may have acquired the +mutex+ and consumed the
1443 * resource before thread +a1+ acquires the +mutex+. This necessitates
1444 * rechecking after +wait+, too.
1445 *
1446 * Example:
1447 *
1448 * mutex = Thread::Mutex.new
1449 *
1450 * resource_available = false
1451 * condvar = Thread::ConditionVariable.new
1452 *
1453 * a1 = Thread.new {
1454 * # Thread 'a1' waits for the resource to become available and consumes
1455 * # the resource.
1456 * mutex.synchronize {
1457 * condvar.wait(mutex) until resource_available
1458 * # After the loop, 'resource_available' is guaranteed to be true.
1459 *
1460 * resource_available = false
1461 * puts "a1 consumed the resource"
1462 * }
1463 * }
1464 *
1465 * a2 = Thread.new {
1466 * # Thread 'a2' behaves like 'a1'.
1467 * mutex.synchronize {
1468 * condvar.wait(mutex) until resource_available
1469 * resource_available = false
1470 * puts "a2 consumed the resource"
1471 * }
1472 * }
1473 *
1474 * b = Thread.new {
1475 * # Thread 'b' periodically makes the resource available.
1476 * loop {
1477 * mutex.synchronize {
1478 * resource_available = true
1479 *
1480 * # Notify one waiting thread if any. It is possible that neither
1481 * # 'a1' nor 'a2 is waiting on 'condvar' at this moment. That's OK.
1482 * condvar.signal
1483 * }
1484 * sleep 1
1485 * }
1486 * }
1487 *
1488 * # Eventually both 'a1' and 'a2' will have their resources, albeit in an
1489 * # unspecified order.
1490 * [a1, a2].each {|th| th.join}
1491 */
1492
1493static size_t
1494condvar_memsize(const void *ptr)
1495{
1496 return sizeof(struct rb_condvar);
1497}
1498
1499static const rb_data_type_t cv_data_type = {
1500 "condvar",
1501 {0, RUBY_TYPED_DEFAULT_FREE, condvar_memsize,},
1502 0, 0, RUBY_TYPED_FREE_IMMEDIATELY|RUBY_TYPED_WB_PROTECTED
1503};
1504
1505static struct rb_condvar *
1506condvar_ptr(VALUE self)
1507{
1508 struct rb_condvar *cv;
1509 rb_serial_t fork_gen = GET_VM()->fork_gen;
1510
1511 TypedData_Get_Struct(self, struct rb_condvar, &cv_data_type, cv);
1512
1513 /* forked children can't reach into parent thread stacks */
1514 if (cv->fork_gen != fork_gen) {
1515 cv->fork_gen = fork_gen;
1516 ccan_list_head_init(&cv->waitq);
1517 }
1518
1519 return cv;
1520}
1521
1522static VALUE
1523condvar_alloc(VALUE klass)
1524{
1525 struct rb_condvar *cv;
1526 VALUE obj;
1527
1528 obj = TypedData_Make_Struct(klass, struct rb_condvar, &cv_data_type, cv);
1529 ccan_list_head_init(&cv->waitq);
1530
1531 return obj;
1532}
1533
1534 struct sleep_call {
1535 rb_execution_context_t *ec;
1536 VALUE mutex;
1537 VALUE timeout;
1538};
1539
1540static ID id_sleep;
1541
1542static VALUE
1543do_sleep(VALUE args)
1544{
1545 struct sleep_call *p = (struct sleep_call *)args;
1546 if (CLASS_OF(p->mutex) == rb_cMutex) {
1547 return rb_mut_sleep(p->ec, p->mutex, p->timeout);
1548 }
1549 else {
1550 return rb_funcallv(p->mutex, id_sleep, 1, &p->timeout);
1551 }
1552}
1553
1554static VALUE
1555rb_condvar_wait(rb_execution_context_t *ec, VALUE self, VALUE mutex, VALUE timeout)
1556{
1557 struct rb_condvar *cv = condvar_ptr(self);
1558 struct sleep_call args = {
1559 .ec = ec,
1560 .mutex = mutex,
1561 .timeout = timeout,
1562 };
1563
1564 struct sync_waiter sync_waiter = {
1565 .self = mutex,
1566 .th = ec->thread_ptr,
1567 .fiber = nonblocking_fiber(ec->fiber_ptr)
1568 };
1569
1570 ccan_list_add_tail(&cv->waitq, &sync_waiter.node);
1571 return rb_ec_ensure(ec, do_sleep, (VALUE)&args, delete_from_waitq, (VALUE)&sync_waiter);
1572}
1573
1574static VALUE
1575rb_condvar_signal(rb_execution_context_t *ec, VALUE self)
1576{
1577 struct rb_condvar *cv = condvar_ptr(self);
1578 wakeup_one(&cv->waitq);
1579 return self;
1580}
1581
1582static VALUE
1583rb_condvar_broadcast(rb_execution_context_t *ec, VALUE self)
1584{
1585 struct rb_condvar *cv = condvar_ptr(self);
1586 wakeup_all(&cv->waitq);
1587 return self;
1588}
1589
1590NORETURN(static VALUE undumpable(VALUE obj));
1591/* :nodoc: */
1592static VALUE
1593undumpable(VALUE obj)
1594{
1595 rb_raise(rb_eTypeError, "can't dump %"PRIsVALUE, rb_obj_class(obj));
1596 UNREACHABLE_RETURN(Qnil);
1597}
1598
1599static VALUE
1600define_thread_class(VALUE outer, const ID name, VALUE super)
1601{
1602 VALUE klass = rb_define_class_id_under(outer, name, super);
1603 rb_const_set(rb_cObject, name, klass);
1604 return klass;
1605}
1606
1607static void
1608Init_thread_sync(void)
1609{
1610#undef rb_intern
1611#if defined(TEACH_RDOC) && TEACH_RDOC == 42
1612 rb_cMutex = rb_define_class_under(rb_cThread, "Mutex", rb_cObject);
1613 rb_cConditionVariable = rb_define_class_under(rb_cThread, "ConditionVariable", rb_cObject);
1614 rb_cQueue = rb_define_class_under(rb_cThread, "Queue", rb_cObject);
1615 rb_cSizedQueue = rb_define_class_under(rb_cThread, "SizedQueue", rb_cObject);
1616#endif
1617
1618#define DEFINE_CLASS(name, super) \
1619 rb_c##name = define_thread_class(rb_cThread, rb_intern(#name), rb_c##super)
1620
1621 /* Mutex */
1622 DEFINE_CLASS(Mutex, Object);
1623 rb_define_alloc_func(rb_cMutex, mutex_alloc);
1624
1625 /* Queue */
1626 DEFINE_CLASS(Queue, Object);
1627 rb_define_alloc_func(rb_cQueue, queue_alloc);
1628
1629 rb_eClosedQueueError = rb_define_class("ClosedQueueError", rb_eStopIteration);
1630
1631 rb_define_method(rb_cQueue, "initialize", rb_queue_initialize, -1);
1632 rb_undef_method(rb_cQueue, "initialize_copy");
1633 rb_define_method(rb_cQueue, "marshal_dump", undumpable, 0);
1634 rb_define_method(rb_cQueue, "close", rb_queue_close, 0);
1635 rb_define_method(rb_cQueue, "closed?", rb_queue_closed_p, 0);
1636 rb_define_method(rb_cQueue, "push", rb_queue_push, 1);
1637 rb_define_method(rb_cQueue, "empty?", rb_queue_empty_p, 0);
1638 rb_define_method(rb_cQueue, "clear", rb_queue_clear, 0);
1639 rb_define_method(rb_cQueue, "length", rb_queue_length, 0);
1640 rb_define_method(rb_cQueue, "num_waiting", rb_queue_num_waiting, 0);
1641 rb_define_method(rb_cQueue, "freeze", rb_queue_freeze, 0);
1642
1643 rb_define_alias(rb_cQueue, "enq", "push");
1644 rb_define_alias(rb_cQueue, "<<", "push");
1645 rb_define_alias(rb_cQueue, "size", "length");
1646
1647 DEFINE_CLASS(SizedQueue, Queue);
1648 rb_define_alloc_func(rb_cSizedQueue, szqueue_alloc);
1649
1650 rb_define_method(rb_cSizedQueue, "initialize", rb_szqueue_initialize, 1);
1651 rb_define_method(rb_cSizedQueue, "close", rb_szqueue_close, 0);
1652 rb_define_method(rb_cSizedQueue, "max", rb_szqueue_max_get, 0);
1653 rb_define_method(rb_cSizedQueue, "max=", rb_szqueue_max_set, 1);
1654 rb_define_method(rb_cSizedQueue, "clear", rb_szqueue_clear, 0);
1655 rb_define_method(rb_cSizedQueue, "num_waiting", rb_szqueue_num_waiting, 0);
1656
1657 /* CVar */
1658 DEFINE_CLASS(ConditionVariable, Object);
1659 rb_define_alloc_func(rb_cConditionVariable, condvar_alloc);
1660
1661 id_sleep = rb_intern("sleep");
1662
1663 rb_provide("thread.rb");
1664}
1665
1666#include "thread_sync.rbinc"
RUBY_ASSERT
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
rb_atomic_t
std::atomic< unsigned > rb_atomic_t
Type that is eligible for atomic operations.
Definition atomic.h:69
rb_define_method
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
Definition cxxanyargs.hpp:670
rb_define_class
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition class.c:1477
rb_define_class_under
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
Defines a class under the namespace of outer.
Definition class.c:1508
rb_define_class_id_under
VALUE rb_define_class_id_under(VALUE outer, ID id, VALUE super)
Identical to rb_define_class_under(), except it takes the name in ID instead of C's string.
Definition class.c:1547
rb_define_alias
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:2842
rb_undef_method
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2654
rb_scan_args
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Retrieves argument from argc and argv to given VALUE references according to the format string.
Definition class.c:3132
FL_UNSET_RAW
#define FL_UNSET_RAW
Old name of RB_FL_UNSET_RAW.
Definition fl_type.h:133
Qundef
#define Qundef
Old name of RUBY_Qundef.
Definition special_consts.h:62
INT2FIX
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
UNREACHABLE_RETURN
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
CLASS_OF
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
FL_TEST_RAW
#define FL_TEST_RAW
Old name of RB_FL_TEST_RAW.
Definition fl_type.h:131
FL_SET
#define FL_SET
Old name of RB_FL_SET.
Definition fl_type.h:128
LONG2NUM
#define LONG2NUM
Old name of RB_LONG2NUM.
Definition long.h:50
Qtrue
#define Qtrue
Old name of RUBY_Qtrue.
Definition special_consts.h:61
INT2NUM
#define INT2NUM
Old name of RB_INT2NUM.
Definition int.h:43
Qnil
#define Qnil
Old name of RUBY_Qnil.
Definition special_consts.h:60
Qfalse
#define Qfalse
Old name of RUBY_Qfalse.
Definition special_consts.h:59
NIL_P
#define NIL_P
Old name of RB_NIL_P.
Definition special_consts.h:55
Check_TypedStruct
#define Check_TypedStruct(v, t)
Old name of rb_check_typeddata.
Definition rtypeddata.h:106
NUM2LONG
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition long.h:51
FIXNUM_P
#define FIXNUM_P
Old name of RB_FIXNUM_P.
Definition special_consts.h:53
FL_SET_RAW
#define FL_SET_RAW
Old name of RB_FL_SET_RAW.
Definition fl_type.h:129
rb_typeddata_is_kind_of
int rb_typeddata_is_kind_of(VALUE obj, const rb_data_type_t *data_type)
Checks if the given object is of given kind.
Definition error.c:1381
rb_eTypeError
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1431
rb_eStopIteration
VALUE rb_eStopIteration
StopIteration exception.
Definition enumerator.c:181
rb_ensure
VALUE rb_ensure(VALUE(*b_proc)(VALUE), VALUE data1, VALUE(*e_proc)(VALUE), VALUE data2)
An equivalent to ensure clause.
Definition eval.c:1172
rb_eThreadError
VALUE rb_eThreadError
ThreadError exception.
Definition eval.c:1039
rb_obj_class
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:264
rb_cThread
VALUE rb_cThread
Thread class.
Definition vm.c:671
rb_num2dbl
double rb_num2dbl(VALUE num)
Converts an instance of rb_cNumeric into C's double.
Definition object.c:3829
rb_equal
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
Definition object.c:176
RB_OBJ_WRITE
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition gc.h:603
rb_ary_concat
VALUE rb_ary_concat(VALUE lhs, VALUE rhs)
Destructively appends the contents of latter into the end of former.
rb_ary_shift
VALUE rb_ary_shift(VALUE ary)
Destructively deletes an element from the beginning of the passed array and returns what was deleted.
rb_ary_hidden_new
VALUE rb_ary_hidden_new(long capa)
Allocates a hidden (no class) empty array.
rb_ary_clear
VALUE rb_ary_clear(VALUE ary)
Destructively removes everything form an array.
rb_ary_push
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
rb_provide
void rb_provide(const char *feature)
Declares that the given feature is already provided by someone else.
Definition load.c:695
rb_mutex_new
VALUE rb_mutex_new(void)
Creates a mutex.
Definition thread_sync.c:184
rb_mutex_trylock
VALUE rb_mutex_trylock(VALUE mutex)
Attempts to lock the mutex, without waiting for other threads to unlock it.
Definition thread_sync.c:260
rb_mutex_locked_p
VALUE rb_mutex_locked_p(VALUE mutex)
Queries if there are any threads that holds the lock.
Definition thread_sync.c:190
rb_mutex_synchronize
VALUE rb_mutex_synchronize(VALUE mutex, VALUE(*func)(VALUE arg), VALUE arg)
Obtains the lock, runs the passed function, and releases the lock when it completes.
Definition thread_sync.c:649
rb_mutex_sleep
VALUE rb_mutex_sleep(VALUE self, VALUE timeout)
Releases the lock held in the mutex and waits for the period of time; reacquires the lock on wakeup.
Definition thread_sync.c:643
rb_mutex_unlock
VALUE rb_mutex_unlock(VALUE mutex)
Releases the mutex.
Definition thread_sync.c:533
rb_mutex_lock
VALUE rb_mutex_lock(VALUE mutex)
Attempts to lock the mutex.
Definition thread_sync.c:450
rb_time_interval
struct timeval rb_time_interval(VALUE num)
Creates a "time interval".
Definition time.c:2949
rb_const_set
void rb_const_set(VALUE space, ID name, VALUE val)
Names a constant.
Definition variable.c:3983
rb_define_alloc_func
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
RARRAY_LEN
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:51
RUBY_TYPED_DEFAULT_FREE
#define RUBY_TYPED_DEFAULT_FREE
This is a value you can set to rb_data_type_struct::dfree.
Definition rtypeddata.h:80
TypedData_Get_Struct
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
Definition rtypeddata.h:649
rb_data_type_t
struct rb_data_type_struct rb_data_type_t
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:205
TypedData_Make_Struct
#define TypedData_Make_Struct(klass, type, data_type, sval)
Identical to TypedData_Wrap_Struct, except it allocates a new data region internally instead of takin...
Definition rtypeddata.h:508
rb_fiber_scheduler_current
VALUE rb_fiber_scheduler_current(void)
Identical to rb_fiber_scheduler_get(), except it also returns RUBY_Qnil in case of a blocking fiber.
Definition scheduler.c:471
rb_fiber_scheduler_block
VALUE rb_fiber_scheduler_block(VALUE scheduler, VALUE blocker, VALUE timeout)
Non-blocking wait for the passed "blocker", which is for instance Thread.join or Mutex....
Definition scheduler.c:660
rb_fiber_scheduler_kernel_sleep
VALUE rb_fiber_scheduler_kernel_sleep(VALUE scheduler, VALUE duration)
Non-blocking sleep.
Definition scheduler.c:543
rb_fiber_scheduler_unblock
VALUE rb_fiber_scheduler_unblock(VALUE scheduler, VALUE blocker, VALUE fiber)
Wakes up a fiber previously blocked using rb_fiber_scheduler_block().
Definition scheduler.c:679
RTEST
#define RTEST
This is an old name of RB_TEST.
Definition special_consts.h:51
mutex_args
Definition thread_sync.c:288
queue_sleep_arg
Definition thread_sync.c:34
queue_waiter
Definition thread_sync.c:1061
rb_condvar
Definition thread_sync.c:1406
rb_mutex_sleep_arguments
Definition thread_sync.c:587
rb_mutex_struct
Definition thread_sync.c:9
rb_queue
Definition thread_sync.c:691
rb_szqueue
Definition thread_sync.c:702
sleep_call
Definition thread_sync.c:1534
sync_waiter
Definition thread_sync.c:17
timeval
Definition missing.h:63
ID
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
VALUE
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
ruby_xfree
void ruby_xfree(void *ptr)
Deallocates a storage instance.
Definition gc.c:5270