Ruby 4.0.10p0 (2026-11-19 revision a704b7cd95a42cc0cf5f307137bf3aac0285b915)
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 */
9typedef 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 */
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
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 }
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
165VALUE
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
183VALUE
185{
186 return mutex_alloc(rb_cMutex);
187}
188
189VALUE
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
259VALUE
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{
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
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
449VALUE
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
463VALUE
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 case THREAD_KILLED: /* not sure about this, possible in exit GC? */
502 /* MSVC 14.52 for ARM64 crashes with /Os on two separate rb_bug calls here */
503 rb_bug("unexpected %s", cur->th->status == THREAD_STOPPED ? "THREAD_STOPPED" : "THREAD_KILLED");
504 }
505 }
506 }
507
508 // We did not find any threads to wake up, so we can just return with no error:
509 return NULL;
510}
511
512static void
513do_mutex_unlock(struct mutex_args *args)
514{
515 const char *err;
516 rb_mutex_t *mutex = args->mutex;
517 rb_thread_t *th = rb_ec_thread_ptr(args->ec);
518
519 err = rb_mutex_unlock_th(mutex, th, rb_ec_serial(args->ec));
520 if (err) rb_raise(rb_eThreadError, "%s", err);
521}
522
523static VALUE
524do_mutex_unlock_safe(VALUE args)
525{
526 do_mutex_unlock((struct mutex_args *)args);
527 return Qnil;
528}
529
530VALUE
532{
533 struct mutex_args args;
534 mutex_args_init(&args, self);
535 do_mutex_unlock(&args);
536 return self;
537}
538
539static VALUE
540rb_mut_unlock(rb_execution_context_t *ec, VALUE self)
541{
542 struct mutex_args args = {
543 .self = self,
544 .mutex = mutex_ptr(self),
545 .ec = ec,
546 };
547 do_mutex_unlock(&args);
548 return self;
549}
550
551#if defined(HAVE_WORKING_FORK)
552static void
553rb_mutex_abandon_keeping_mutexes(rb_thread_t *th)
554{
555 rb_mutex_abandon_all(th->keeping_mutexes);
556 th->keeping_mutexes = NULL;
557}
558
559static void
560rb_mutex_abandon_locking_mutex(rb_thread_t *th)
561{
562 if (th->locking_mutex) {
563 rb_mutex_t *mutex = mutex_ptr(th->locking_mutex);
564
565 ccan_list_head_init(&mutex->waitq);
566 th->locking_mutex = Qfalse;
567 }
568}
569
570static void
571rb_mutex_abandon_all(rb_mutex_t *mutexes)
572{
573 rb_mutex_t *mutex;
574
575 while (mutexes) {
576 mutex = mutexes;
577 mutexes = mutex->next_mutex;
578 mutex->ec_serial = 0;
579 mutex->next_mutex = 0;
580 ccan_list_head_init(&mutex->waitq);
581 }
582}
583#endif
584
586 VALUE self;
587 VALUE timeout;
588};
589
590static VALUE
591mutex_sleep_begin(VALUE _arguments)
592{
593 struct rb_mutex_sleep_arguments *arguments = (struct rb_mutex_sleep_arguments *)_arguments;
594 VALUE timeout = arguments->timeout;
595 VALUE woken = Qtrue;
596
597 VALUE scheduler = rb_fiber_scheduler_current();
598 if (scheduler != Qnil) {
599 rb_fiber_scheduler_kernel_sleep(scheduler, timeout);
600 }
601 else {
602 if (NIL_P(timeout)) {
603 rb_thread_sleep_deadly_allow_spurious_wakeup(arguments->self, Qnil, 0);
604 }
605 else {
606 struct timeval timeout_value = rb_time_interval(timeout);
607 rb_hrtime_t relative_timeout = rb_timeval2hrtime(&timeout_value);
608 /* permit spurious check */
609 woken = RBOOL(sleep_hrtime(GET_THREAD(), relative_timeout, 0));
610 }
611 }
612
613 return woken;
614}
615
616static VALUE
617rb_mut_sleep(rb_execution_context_t *ec, VALUE self, VALUE timeout)
618{
619 if (!NIL_P(timeout)) {
620 // Validate the argument:
621 rb_time_interval(timeout);
622 }
623
624 rb_mut_unlock(ec, self);
625 time_t beg = time(0);
626
627 struct rb_mutex_sleep_arguments arguments = {
628 .self = self,
629 .timeout = timeout,
630 };
631
632 VALUE woken = rb_ec_ensure(ec, mutex_sleep_begin, (VALUE)&arguments, mutex_lock_uninterruptible, self);
633
634 RUBY_VM_CHECK_INTS_BLOCKING(ec);
635 if (!woken) return Qnil;
636 time_t end = time(0) - beg;
637 return TIMET2NUM(end);
638}
639
640VALUE
642{
643 return rb_mut_sleep(GET_EC(), self, timeout);
644}
645
646VALUE
648{
649 struct mutex_args args;
650 mutex_args_init(&args, self);
651 do_mutex_lock(&args, 1);
652 return rb_ec_ensure(args.ec, func, arg, do_mutex_unlock_safe, (VALUE)&args);
653}
654
655static VALUE
656do_ec_yield(VALUE _ec)
657{
658 return rb_ec_yield((rb_execution_context_t *)_ec, Qundef);
659}
660
661VALUE
662rb_mut_synchronize(rb_execution_context_t *ec, VALUE self)
663{
664 struct mutex_args args = {
665 .self = self,
666 .mutex = mutex_ptr(self),
667 .ec = ec,
668 };
669 do_mutex_lock(&args, 1);
670 return rb_ec_ensure(args.ec, do_ec_yield, (VALUE)ec, do_mutex_unlock_safe, (VALUE)&args);
671}
672
673void
674rb_mutex_allow_trap(VALUE self, int val)
675{
676 Check_TypedStruct(self, &mutex_data_type);
677
678 if (val)
679 FL_SET_RAW(self, MUTEX_ALLOW_TRAP);
680 else
681 FL_UNSET_RAW(self, MUTEX_ALLOW_TRAP);
682}
683
684/* Queue */
685
686#define queue_waitq(q) UNALIGNED_MEMBER_PTR(q, waitq)
687#define queue_list(q) UNALIGNED_MEMBER_PTR(q, que)
688RBIMPL_ATTR_PACKED_STRUCT_UNALIGNED_BEGIN()
689struct rb_queue {
690 struct ccan_list_head waitq;
691 rb_serial_t fork_gen;
692 const VALUE que;
693 int num_waiting;
694} RBIMPL_ATTR_PACKED_STRUCT_UNALIGNED_END();
695
696#define szqueue_waitq(sq) UNALIGNED_MEMBER_PTR(sq, q.waitq)
697#define szqueue_list(sq) UNALIGNED_MEMBER_PTR(sq, q.que)
698#define szqueue_pushq(sq) UNALIGNED_MEMBER_PTR(sq, pushq)
699RBIMPL_ATTR_PACKED_STRUCT_UNALIGNED_BEGIN()
701 struct rb_queue q;
702 int num_waiting_push;
703 struct ccan_list_head pushq;
704 long max;
705} RBIMPL_ATTR_PACKED_STRUCT_UNALIGNED_END();
706
707static void
708queue_mark_and_move(void *ptr)
709{
710 struct rb_queue *q = ptr;
711
712 /* no need to mark threads in waitq, they are on stack */
713 rb_gc_mark_and_move((VALUE *)UNALIGNED_MEMBER_PTR(q, que));
714}
715
716static size_t
717queue_memsize(const void *ptr)
718{
719 return sizeof(struct rb_queue);
720}
721
722static const rb_data_type_t queue_data_type = {
723 .wrap_struct_name = "Thread::Queue",
724 .function = {
725 .dmark = queue_mark_and_move,
727 .dsize = queue_memsize,
728 .dcompact = queue_mark_and_move,
729 },
730 .flags = RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED,
731};
732
733static VALUE
734queue_alloc(VALUE klass)
735{
736 VALUE obj;
737 struct rb_queue *q;
738
739 obj = TypedData_Make_Struct(klass, struct rb_queue, &queue_data_type, q);
740 ccan_list_head_init(queue_waitq(q));
741 return obj;
742}
743
744static int
745queue_fork_check(struct rb_queue *q)
746{
747 rb_serial_t fork_gen = GET_VM()->fork_gen;
748
749 if (q->fork_gen == fork_gen) {
750 return 0;
751 }
752 /* forked children can't reach into parent thread stacks */
753 q->fork_gen = fork_gen;
754 ccan_list_head_init(queue_waitq(q));
755 q->num_waiting = 0;
756 return 1;
757}
758
759static struct rb_queue *
760queue_ptr(VALUE obj)
761{
762 struct rb_queue *q;
763
764 TypedData_Get_Struct(obj, struct rb_queue, &queue_data_type, q);
765 queue_fork_check(q);
766
767 return q;
768}
769
770#define QUEUE_CLOSED FL_USER5
771
772static rb_hrtime_t
773queue_timeout2hrtime(VALUE timeout)
774{
775 if (NIL_P(timeout)) {
776 return (rb_hrtime_t)0;
777 }
778 rb_hrtime_t rel = 0;
779 if (FIXNUM_P(timeout)) {
780 rel = rb_sec2hrtime(NUM2TIMET(timeout));
781 }
782 else {
783 double2hrtime(&rel, rb_num2dbl(timeout));
784 }
785 return rb_hrtime_add(rel, rb_hrtime_now());
786}
787
788static void
789szqueue_mark_and_move(void *ptr)
790{
791 struct rb_szqueue *sq = ptr;
792
793 queue_mark_and_move(&sq->q);
794}
795
796static size_t
797szqueue_memsize(const void *ptr)
798{
799 return sizeof(struct rb_szqueue);
800}
801
802static const rb_data_type_t szqueue_data_type = {
803 .wrap_struct_name = "Thread::SizedQueue",
804 .function = {
805 .dmark = szqueue_mark_and_move,
807 .dsize = szqueue_memsize,
808 .dcompact = szqueue_mark_and_move,
809 },
810 .parent = &queue_data_type,
811 .flags = RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED,
812};
813
814static VALUE
815szqueue_alloc(VALUE klass)
816{
817 struct rb_szqueue *sq;
818 VALUE obj = TypedData_Make_Struct(klass, struct rb_szqueue,
819 &szqueue_data_type, sq);
820 ccan_list_head_init(szqueue_waitq(sq));
821 ccan_list_head_init(szqueue_pushq(sq));
822 return obj;
823}
824
825static struct rb_szqueue *
826szqueue_ptr(VALUE obj)
827{
828 struct rb_szqueue *sq;
829
830 TypedData_Get_Struct(obj, struct rb_szqueue, &szqueue_data_type, sq);
831 if (queue_fork_check(&sq->q)) {
832 ccan_list_head_init(szqueue_pushq(sq));
833 sq->num_waiting_push = 0;
834 }
835
836 return sq;
837}
838
839static VALUE
840ary_buf_new(void)
841{
842 return rb_ary_hidden_new(1);
843}
844
845static inline VALUE
846check_array(VALUE obj, VALUE ary)
847{
848 if (RB_LIKELY(ary)) {
849 return ary;
850 }
851 rb_raise(rb_eTypeError, "%+"PRIsVALUE" not initialized", obj);
852}
853
854static long
855queue_length(VALUE self, struct rb_queue *q)
856{
857 return RARRAY_LEN(check_array(self, q->que));
858}
859
860static int
861queue_closed_p(VALUE self)
862{
863 return FL_TEST_RAW(self, QUEUE_CLOSED) != 0;
864}
865
866/*
867 * Document-class: ClosedQueueError
868 *
869 * The exception class which will be raised when pushing into a closed
870 * Queue. See Thread::Queue#close and Thread::SizedQueue#close.
871 */
872
873NORETURN(static void raise_closed_queue_error(VALUE self));
874
875static void
876raise_closed_queue_error(VALUE self)
877{
878 rb_raise(rb_eClosedQueueError, "queue closed");
879}
880
881static VALUE
882queue_closed_result(VALUE self, struct rb_queue *q)
883{
884 RUBY_ASSERT(queue_length(self, q) == 0);
885 return Qnil;
886}
887
888/*
889 * Document-class: Thread::Queue
890 *
891 * The Thread::Queue class implements multi-producer, multi-consumer
892 * queues. It is especially useful in threaded programming when
893 * information must be exchanged safely between multiple threads. The
894 * Thread::Queue class implements all the required locking semantics.
895 *
896 * The class implements FIFO (first in, first out) type of queue.
897 * In a FIFO queue, the first tasks added are the first retrieved.
898 *
899 * Example:
900 *
901 * queue = Thread::Queue.new
902 *
903 * producer = Thread.new do
904 * 5.times do |i|
905 * sleep rand(i) # simulate expense
906 * queue << i
907 * puts "#{i} produced"
908 * end
909 * end
910 *
911 * consumer = Thread.new do
912 * 5.times do |i|
913 * value = queue.pop
914 * sleep rand(i/2) # simulate expense
915 * puts "consumed #{value}"
916 * end
917 * end
918 *
919 * consumer.join
920 *
921 */
922
923/*
924 * Document-method: Queue::new
925 *
926 * call-seq:
927 * Thread::Queue.new -> empty_queue
928 * Thread::Queue.new(enumerable) -> queue
929 *
930 * Creates a new queue instance, optionally using the contents of an +enumerable+
931 * for its initial state.
932 *
933 * Example:
934 *
935 * q = Thread::Queue.new
936 * #=> #<Thread::Queue:0x00007ff7501110d0>
937 * q.empty?
938 * #=> true
939 *
940 * q = Thread::Queue.new([1, 2, 3])
941 * #=> #<Thread::Queue:0x00007ff7500ec500>
942 * q.empty?
943 * #=> false
944 * q.pop
945 * #=> 1
946 */
947
948static VALUE
949rb_queue_initialize(int argc, VALUE *argv, VALUE self)
950{
951 VALUE initial;
952 struct rb_queue *q = queue_ptr(self);
953 if ((argc = rb_scan_args(argc, argv, "01", &initial)) == 1) {
954 initial = rb_to_array(initial);
955 }
956 RB_OBJ_WRITE(self, queue_list(q), ary_buf_new());
957 ccan_list_head_init(queue_waitq(q));
958 if (argc == 1) {
959 rb_ary_concat(q->que, initial);
960 }
961 return self;
962}
963
964static VALUE
965queue_do_push(VALUE self, struct rb_queue *q, VALUE obj)
966{
967 if (queue_closed_p(self)) {
968 raise_closed_queue_error(self);
969 }
970 rb_ary_push(check_array(self, q->que), obj);
971 wakeup_one(queue_waitq(q));
972 return self;
973}
974
975/*
976 * Document-method: Thread::Queue#close
977 * call-seq:
978 * close
979 *
980 * Closes the queue. A closed queue cannot be re-opened.
981 *
982 * After the call to close completes, the following are true:
983 *
984 * - +closed?+ will return true
985 *
986 * - +close+ will be ignored.
987 *
988 * - calling enq/push/<< will raise a +ClosedQueueError+.
989 *
990 * - when +empty?+ is false, calling deq/pop/shift will return an object
991 * from the queue as usual.
992 * - when +empty?+ is true, deq(false) will not suspend the thread and will return nil.
993 * deq(true) will raise a +ThreadError+.
994 *
995 * ClosedQueueError is inherited from StopIteration, so that you can break loop block.
996 *
997 * Example:
998 *
999 * q = Thread::Queue.new
1000 * Thread.new{
1001 * while e = q.deq # wait for nil to break loop
1002 * # ...
1003 * end
1004 * }
1005 * q.close
1006 */
1007
1008static VALUE
1009rb_queue_close(VALUE self)
1010{
1011 struct rb_queue *q = queue_ptr(self);
1012
1013 if (!queue_closed_p(self)) {
1014 FL_SET(self, QUEUE_CLOSED);
1015
1016 wakeup_all(queue_waitq(q));
1017 }
1018
1019 return self;
1020}
1021
1022/*
1023 * Document-method: Thread::Queue#closed?
1024 * call-seq: closed?
1025 *
1026 * Returns +true+ if the queue is closed.
1027 */
1028
1029static VALUE
1030rb_queue_closed_p(VALUE self)
1031{
1032 return RBOOL(queue_closed_p(self));
1033}
1034
1035/*
1036 * Document-method: Thread::Queue#push
1037 * call-seq:
1038 * push(object)
1039 * enq(object)
1040 * <<(object)
1041 *
1042 * Pushes the given +object+ to the queue.
1043 */
1044
1045static VALUE
1046rb_queue_push(VALUE self, VALUE obj)
1047{
1048 return queue_do_push(self, queue_ptr(self), obj);
1049}
1050
1051static VALUE
1052queue_sleep(VALUE _args)
1053{
1054 struct queue_sleep_arg *args = (struct queue_sleep_arg *)_args;
1055 rb_thread_sleep_deadly_allow_spurious_wakeup(args->self, args->timeout, args->end);
1056 return Qnil;
1057}
1058
1060 struct sync_waiter w;
1061 union {
1062 struct rb_queue *q;
1063 struct rb_szqueue *sq;
1064 } as;
1065};
1066
1067static VALUE
1068queue_sleep_done(VALUE p)
1069{
1070 struct queue_waiter *qw = (struct queue_waiter *)p;
1071
1072 ccan_list_del(&qw->w.node);
1073 qw->as.q->num_waiting--;
1074
1075 return Qfalse;
1076}
1077
1078static VALUE
1079szqueue_sleep_done(VALUE p)
1080{
1081 struct queue_waiter *qw = (struct queue_waiter *)p;
1082
1083 ccan_list_del(&qw->w.node);
1084 qw->as.sq->num_waiting_push--;
1085
1086 return Qfalse;
1087}
1088
1089static inline VALUE
1090queue_do_pop(rb_execution_context_t *ec, VALUE self, struct rb_queue *q, VALUE non_block, VALUE timeout)
1091{
1092 check_array(self, q->que);
1093 if (RARRAY_LEN(q->que) == 0) {
1094 if (RTEST(non_block)) {
1095 rb_raise(rb_eThreadError, "queue empty");
1096 }
1097
1098 if (RTEST(rb_equal(INT2FIX(0), timeout))) {
1099 return Qnil;
1100 }
1101 }
1102
1103 rb_hrtime_t end = queue_timeout2hrtime(timeout);
1104 while (RARRAY_LEN(q->que) == 0) {
1105 if (queue_closed_p(self)) {
1106 return queue_closed_result(self, q);
1107 }
1108 else {
1109 RUBY_ASSERT(RARRAY_LEN(q->que) == 0);
1110 RUBY_ASSERT(queue_closed_p(self) == 0);
1111
1112 struct queue_waiter queue_waiter = {
1113 .w = {.self = self, .th = ec->thread_ptr, .fiber = nonblocking_fiber(ec->fiber_ptr)},
1114 .as = {.q = q}
1115 };
1116
1117 struct ccan_list_head *waitq = queue_waitq(q);
1118
1119 ccan_list_add_tail(waitq, &queue_waiter.w.node);
1120 queue_waiter.as.q->num_waiting++;
1121
1123 .self = self,
1124 .timeout = timeout,
1125 .end = end
1126 };
1127
1128 rb_ensure(queue_sleep, (VALUE)&queue_sleep_arg, queue_sleep_done, (VALUE)&queue_waiter);
1129 if (!NIL_P(timeout) && (rb_hrtime_now() >= end))
1130 break;
1131 }
1132 }
1133
1134 return rb_ary_shift(q->que);
1135}
1136
1137static VALUE
1138rb_queue_pop(rb_execution_context_t *ec, VALUE self, VALUE non_block, VALUE timeout)
1139{
1140 return queue_do_pop(ec, self, queue_ptr(self), non_block, timeout);
1141}
1142
1143/*
1144 * Document-method: Thread::Queue#empty?
1145 * call-seq: empty?
1146 *
1147 * Returns +true+ if the queue is empty.
1148 */
1149
1150static VALUE
1151rb_queue_empty_p(VALUE self)
1152{
1153 return RBOOL(queue_length(self, queue_ptr(self)) == 0);
1154}
1155
1156/*
1157 * Document-method: Thread::Queue#clear
1158 *
1159 * Removes all objects from the queue.
1160 */
1161
1162static VALUE
1163rb_queue_clear(VALUE self)
1164{
1165 struct rb_queue *q = queue_ptr(self);
1166
1167 rb_ary_clear(check_array(self, q->que));
1168 return self;
1169}
1170
1171/*
1172 * Document-method: Thread::Queue#length
1173 * call-seq:
1174 * length
1175 * size
1176 *
1177 * Returns the length of the queue.
1178 */
1179
1180static VALUE
1181rb_queue_length(VALUE self)
1182{
1183 return LONG2NUM(queue_length(self, queue_ptr(self)));
1184}
1185
1186NORETURN(static VALUE rb_queue_freeze(VALUE self));
1187/*
1188 * call-seq:
1189 * freeze
1190 *
1191 * The queue can't be frozen, so this method raises an exception:
1192 * Thread::Queue.new.freeze # Raises TypeError (cannot freeze #<Thread::Queue:0x...>)
1193 *
1194 */
1195static VALUE
1196rb_queue_freeze(VALUE self)
1197{
1198 rb_raise(rb_eTypeError, "cannot freeze " "%+"PRIsVALUE, self);
1199 UNREACHABLE_RETURN(self);
1200}
1201
1202/*
1203 * Document-method: Thread::Queue#num_waiting
1204 *
1205 * Returns the number of threads waiting on the queue.
1206 */
1207
1208static VALUE
1209rb_queue_num_waiting(VALUE self)
1210{
1211 struct rb_queue *q = queue_ptr(self);
1212
1213 return INT2NUM(q->num_waiting);
1214}
1215
1216/*
1217 * Document-class: Thread::SizedQueue
1218 *
1219 * This class represents queues of specified size capacity. The push operation
1220 * may be blocked if the capacity is full.
1221 *
1222 * See Thread::Queue for an example of how a Thread::SizedQueue works.
1223 */
1224
1225/*
1226 * Document-method: SizedQueue::new
1227 * call-seq: new(max)
1228 *
1229 * Creates a fixed-length queue with a maximum size of +max+.
1230 */
1231
1232static VALUE
1233rb_szqueue_initialize(VALUE self, VALUE vmax)
1234{
1235 long max;
1236 struct rb_szqueue *sq = szqueue_ptr(self);
1237
1238 max = NUM2LONG(vmax);
1239 if (max <= 0) {
1240 rb_raise(rb_eArgError, "queue size must be positive");
1241 }
1242
1243 RB_OBJ_WRITE(self, szqueue_list(sq), ary_buf_new());
1244 ccan_list_head_init(szqueue_waitq(sq));
1245 ccan_list_head_init(szqueue_pushq(sq));
1246 sq->max = max;
1247
1248 return self;
1249}
1250
1251/*
1252 * Document-method: Thread::SizedQueue#close
1253 * call-seq:
1254 * close
1255 *
1256 * Similar to Thread::Queue#close.
1257 *
1258 * The difference is behavior with waiting enqueuing threads.
1259 *
1260 * If there are waiting enqueuing threads, they are interrupted by
1261 * raising ClosedQueueError('queue closed').
1262 */
1263static VALUE
1264rb_szqueue_close(VALUE self)
1265{
1266 if (!queue_closed_p(self)) {
1267 struct rb_szqueue *sq = szqueue_ptr(self);
1268
1269 FL_SET(self, QUEUE_CLOSED);
1270 wakeup_all(szqueue_waitq(sq));
1271 wakeup_all(szqueue_pushq(sq));
1272 }
1273 return self;
1274}
1275
1276/*
1277 * Document-method: Thread::SizedQueue#max
1278 *
1279 * Returns the maximum size of the queue.
1280 */
1281
1282static VALUE
1283rb_szqueue_max_get(VALUE self)
1284{
1285 return LONG2NUM(szqueue_ptr(self)->max);
1286}
1287
1288/*
1289 * Document-method: Thread::SizedQueue#max=
1290 * call-seq: max=(number)
1291 *
1292 * Sets the maximum size of the queue to the given +number+.
1293 */
1294
1295static VALUE
1296rb_szqueue_max_set(VALUE self, VALUE vmax)
1297{
1298 long max = NUM2LONG(vmax);
1299 long diff = 0;
1300 struct rb_szqueue *sq = szqueue_ptr(self);
1301
1302 if (max <= 0) {
1303 rb_raise(rb_eArgError, "queue size must be positive");
1304 }
1305 if (max > sq->max) {
1306 diff = max - sq->max;
1307 }
1308 sq->max = max;
1309 sync_wakeup(szqueue_pushq(sq), diff);
1310 return vmax;
1311}
1312
1313static VALUE
1314rb_szqueue_push(rb_execution_context_t *ec, VALUE self, VALUE object, VALUE non_block, VALUE timeout)
1315{
1316 struct rb_szqueue *sq = szqueue_ptr(self);
1317
1318 if (queue_length(self, &sq->q) >= sq->max) {
1319 if (RTEST(non_block)) {
1320 rb_raise(rb_eThreadError, "queue full");
1321 }
1322
1323 if (RTEST(rb_equal(INT2FIX(0), timeout))) {
1324 return Qnil;
1325 }
1326 }
1327
1328 rb_hrtime_t end = queue_timeout2hrtime(timeout);
1329 while (queue_length(self, &sq->q) >= sq->max) {
1330 if (queue_closed_p(self)) {
1331 raise_closed_queue_error(self);
1332 }
1333 else {
1334 struct queue_waiter queue_waiter = {
1335 .w = {.self = self, .th = ec->thread_ptr, .fiber = nonblocking_fiber(ec->fiber_ptr)},
1336 .as = {.sq = sq}
1337 };
1338
1339 struct ccan_list_head *pushq = szqueue_pushq(sq);
1340
1341 ccan_list_add_tail(pushq, &queue_waiter.w.node);
1342 sq->num_waiting_push++;
1343
1345 .self = self,
1346 .timeout = timeout,
1347 .end = end
1348 };
1349 rb_ensure(queue_sleep, (VALUE)&queue_sleep_arg, szqueue_sleep_done, (VALUE)&queue_waiter);
1350 if (!NIL_P(timeout) && rb_hrtime_now() >= end) {
1351 return Qnil;
1352 }
1353 }
1354 }
1355
1356 return queue_do_push(self, &sq->q, object);
1357}
1358
1359static VALUE
1360rb_szqueue_pop(rb_execution_context_t *ec, VALUE self, VALUE non_block, VALUE timeout)
1361{
1362 struct rb_szqueue *sq = szqueue_ptr(self);
1363 VALUE retval = queue_do_pop(ec, self, &sq->q, non_block, timeout);
1364
1365 if (queue_length(self, &sq->q) < sq->max) {
1366 wakeup_one(szqueue_pushq(sq));
1367 }
1368
1369 return retval;
1370}
1371
1372/*
1373 * Document-method: Thread::SizedQueue#clear
1374 *
1375 * Removes all objects from the queue.
1376 */
1377
1378static VALUE
1379rb_szqueue_clear(VALUE self)
1380{
1381 struct rb_szqueue *sq = szqueue_ptr(self);
1382
1383 rb_ary_clear(check_array(self, sq->q.que));
1384 wakeup_all(szqueue_pushq(sq));
1385 return self;
1386}
1387
1388/*
1389 * Document-method: Thread::SizedQueue#num_waiting
1390 *
1391 * Returns the number of threads waiting on the queue.
1392 */
1393
1394static VALUE
1395rb_szqueue_num_waiting(VALUE self)
1396{
1397 struct rb_szqueue *sq = szqueue_ptr(self);
1398
1399 return INT2NUM(sq->q.num_waiting + sq->num_waiting_push);
1400}
1401
1402
1403/* ConditionalVariable */
1405 struct ccan_list_head waitq;
1406 rb_serial_t fork_gen;
1407};
1408
1409/*
1410 * Document-class: Thread::ConditionVariable
1411 *
1412 * ConditionVariable objects augment class Mutex. Using condition variables,
1413 * it is possible to suspend while in the middle of a critical section until a
1414 * condition is met, such as a resource becomes available.
1415 *
1416 * Due to non-deterministic scheduling and spurious wake-ups, users of
1417 * condition variables should always use a separate boolean predicate (such as
1418 * reading from a boolean variable) to check if the condition is actually met
1419 * before starting to wait, and should wait in a loop, re-checking the
1420 * condition every time the ConditionVariable is waken up. The idiomatic way
1421 * of using condition variables is calling the +wait+ method in an +until+
1422 * loop with the predicate as the loop condition.
1423 *
1424 * condvar.wait(mutex) until condition_is_met
1425 *
1426 * In the example below, we use the boolean variable +resource_available+
1427 * (which is protected by +mutex+) to indicate the availability of the
1428 * resource, and use +condvar+ to wait for that variable to become true. Note
1429 * that:
1430 *
1431 * 1. Thread +b+ may be scheduled before thread +a1+ and +a2+, and may run so
1432 * fast that it have already made the resource available before either
1433 * +a1+ or +a2+ starts. Therefore, +a1+ and +a2+ should check if
1434 * +resource_available+ is already true before starting to wait.
1435 * 2. The +wait+ method may spuriously wake up without signalling. Therefore,
1436 * thread +a1+ and +a2+ should recheck +resource_available+ after the
1437 * +wait+ method returns, and go back to wait if the condition is not
1438 * actually met.
1439 * 3. It is possible that thread +a2+ starts right after thread +a1+ is waken
1440 * up by +b+. Thread +a2+ may have acquired the +mutex+ and consumed the
1441 * resource before thread +a1+ acquires the +mutex+. This necessitates
1442 * rechecking after +wait+, too.
1443 *
1444 * Example:
1445 *
1446 * mutex = Thread::Mutex.new
1447 *
1448 * resource_available = false
1449 * condvar = Thread::ConditionVariable.new
1450 *
1451 * a1 = Thread.new {
1452 * # Thread 'a1' waits for the resource to become available and consumes
1453 * # the resource.
1454 * mutex.synchronize {
1455 * condvar.wait(mutex) until resource_available
1456 * # After the loop, 'resource_available' is guaranteed to be true.
1457 *
1458 * resource_available = false
1459 * puts "a1 consumed the resource"
1460 * }
1461 * }
1462 *
1463 * a2 = Thread.new {
1464 * # Thread 'a2' behaves like 'a1'.
1465 * mutex.synchronize {
1466 * condvar.wait(mutex) until resource_available
1467 * resource_available = false
1468 * puts "a2 consumed the resource"
1469 * }
1470 * }
1471 *
1472 * b = Thread.new {
1473 * # Thread 'b' periodically makes the resource available.
1474 * loop {
1475 * mutex.synchronize {
1476 * resource_available = true
1477 *
1478 * # Notify one waiting thread if any. It is possible that neither
1479 * # 'a1' nor 'a2 is waiting on 'condvar' at this moment. That's OK.
1480 * condvar.signal
1481 * }
1482 * sleep 1
1483 * }
1484 * }
1485 *
1486 * # Eventually both 'a1' and 'a2' will have their resources, albeit in an
1487 * # unspecified order.
1488 * [a1, a2].each {|th| th.join}
1489 */
1490
1491static size_t
1492condvar_memsize(const void *ptr)
1493{
1494 return sizeof(struct rb_condvar);
1495}
1496
1497static const rb_data_type_t cv_data_type = {
1498 "condvar",
1499 {0, RUBY_TYPED_DEFAULT_FREE, condvar_memsize,},
1500 0, 0, RUBY_TYPED_FREE_IMMEDIATELY|RUBY_TYPED_WB_PROTECTED
1501};
1502
1503static struct rb_condvar *
1504condvar_ptr(VALUE self)
1505{
1506 struct rb_condvar *cv;
1507 rb_serial_t fork_gen = GET_VM()->fork_gen;
1508
1509 TypedData_Get_Struct(self, struct rb_condvar, &cv_data_type, cv);
1510
1511 /* forked children can't reach into parent thread stacks */
1512 if (cv->fork_gen != fork_gen) {
1513 cv->fork_gen = fork_gen;
1514 ccan_list_head_init(&cv->waitq);
1515 }
1516
1517 return cv;
1518}
1519
1520static VALUE
1521condvar_alloc(VALUE klass)
1522{
1523 struct rb_condvar *cv;
1524 VALUE obj;
1525
1526 obj = TypedData_Make_Struct(klass, struct rb_condvar, &cv_data_type, cv);
1527 ccan_list_head_init(&cv->waitq);
1528
1529 return obj;
1530}
1531
1533 rb_execution_context_t *ec;
1534 VALUE mutex;
1535 VALUE timeout;
1536};
1537
1538static ID id_sleep;
1539
1540static VALUE
1541do_sleep(VALUE args)
1542{
1543 struct sleep_call *p = (struct sleep_call *)args;
1544 if (CLASS_OF(p->mutex) == rb_cMutex) {
1545 return rb_mut_sleep(p->ec, p->mutex, p->timeout);
1546 }
1547 else {
1548 return rb_funcallv(p->mutex, id_sleep, 1, &p->timeout);
1549 }
1550}
1551
1552static VALUE
1553rb_condvar_wait(rb_execution_context_t *ec, VALUE self, VALUE mutex, VALUE timeout)
1554{
1555 struct rb_condvar *cv = condvar_ptr(self);
1556 struct sleep_call args = {
1557 .ec = ec,
1558 .mutex = mutex,
1559 .timeout = timeout,
1560 };
1561
1562 struct sync_waiter sync_waiter = {
1563 .self = mutex,
1564 .th = ec->thread_ptr,
1565 .fiber = nonblocking_fiber(ec->fiber_ptr)
1566 };
1567
1568 ccan_list_add_tail(&cv->waitq, &sync_waiter.node);
1569 return rb_ec_ensure(ec, do_sleep, (VALUE)&args, delete_from_waitq, (VALUE)&sync_waiter);
1570}
1571
1572static VALUE
1573rb_condvar_signal(rb_execution_context_t *ec, VALUE self)
1574{
1575 struct rb_condvar *cv = condvar_ptr(self);
1576 wakeup_one(&cv->waitq);
1577 return self;
1578}
1579
1580static VALUE
1581rb_condvar_broadcast(rb_execution_context_t *ec, VALUE self)
1582{
1583 struct rb_condvar *cv = condvar_ptr(self);
1584 wakeup_all(&cv->waitq);
1585 return self;
1586}
1587
1588NORETURN(static VALUE undumpable(VALUE obj));
1589/* :nodoc: */
1590static VALUE
1591undumpable(VALUE obj)
1592{
1593 rb_raise(rb_eTypeError, "can't dump %"PRIsVALUE, rb_obj_class(obj));
1595}
1596
1597static VALUE
1598define_thread_class(VALUE outer, const ID name, VALUE super)
1599{
1600 VALUE klass = rb_define_class_id_under(outer, name, super);
1601 rb_const_set(rb_cObject, name, klass);
1602 return klass;
1603}
1604
1605static void
1606Init_thread_sync(void)
1607{
1608#undef rb_intern
1609#if defined(TEACH_RDOC) && TEACH_RDOC == 42
1610 rb_cMutex = rb_define_class_under(rb_cThread, "Mutex", rb_cObject);
1611 rb_cConditionVariable = rb_define_class_under(rb_cThread, "ConditionVariable", rb_cObject);
1612 rb_cQueue = rb_define_class_under(rb_cThread, "Queue", rb_cObject);
1613 rb_cSizedQueue = rb_define_class_under(rb_cThread, "SizedQueue", rb_cObject);
1614#endif
1615
1616#define DEFINE_CLASS(name, super) \
1617 rb_c##name = define_thread_class(rb_cThread, rb_intern(#name), rb_c##super)
1618
1619 /* Mutex */
1620 DEFINE_CLASS(Mutex, Object);
1621 rb_define_alloc_func(rb_cMutex, mutex_alloc);
1622
1623 /* Queue */
1624 DEFINE_CLASS(Queue, Object);
1625 rb_define_alloc_func(rb_cQueue, queue_alloc);
1626
1627 rb_eClosedQueueError = rb_define_class("ClosedQueueError", rb_eStopIteration);
1628
1629 rb_define_method(rb_cQueue, "initialize", rb_queue_initialize, -1);
1630 rb_undef_method(rb_cQueue, "initialize_copy");
1631 rb_define_method(rb_cQueue, "marshal_dump", undumpable, 0);
1632 rb_define_method(rb_cQueue, "close", rb_queue_close, 0);
1633 rb_define_method(rb_cQueue, "closed?", rb_queue_closed_p, 0);
1634 rb_define_method(rb_cQueue, "push", rb_queue_push, 1);
1635 rb_define_method(rb_cQueue, "empty?", rb_queue_empty_p, 0);
1636 rb_define_method(rb_cQueue, "clear", rb_queue_clear, 0);
1637 rb_define_method(rb_cQueue, "length", rb_queue_length, 0);
1638 rb_define_method(rb_cQueue, "num_waiting", rb_queue_num_waiting, 0);
1639 rb_define_method(rb_cQueue, "freeze", rb_queue_freeze, 0);
1640
1641 rb_define_alias(rb_cQueue, "enq", "push");
1642 rb_define_alias(rb_cQueue, "<<", "push");
1643 rb_define_alias(rb_cQueue, "size", "length");
1644
1645 DEFINE_CLASS(SizedQueue, Queue);
1646 rb_define_alloc_func(rb_cSizedQueue, szqueue_alloc);
1647
1648 rb_define_method(rb_cSizedQueue, "initialize", rb_szqueue_initialize, 1);
1649 rb_define_method(rb_cSizedQueue, "close", rb_szqueue_close, 0);
1650 rb_define_method(rb_cSizedQueue, "max", rb_szqueue_max_get, 0);
1651 rb_define_method(rb_cSizedQueue, "max=", rb_szqueue_max_set, 1);
1652 rb_define_method(rb_cSizedQueue, "clear", rb_szqueue_clear, 0);
1653 rb_define_method(rb_cSizedQueue, "num_waiting", rb_szqueue_num_waiting, 0);
1654
1655 /* CVar */
1656 DEFINE_CLASS(ConditionVariable, Object);
1657 rb_define_alloc_func(rb_cConditionVariable, condvar_alloc);
1658
1659 id_sleep = rb_intern("sleep");
1660
1661 rb_provide("thread.rb");
1662}
1663
1664#include "thread_sync.rbinc"
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
std::atomic< unsigned > rb_atomic_t
Type that is eligible for atomic operations.
Definition atomic.h:69
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition class.c:1488
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
Defines a class under the namespace of outer.
Definition class.c:1519
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:1558
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:2868
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2680
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:3158
#define FL_UNSET_RAW
Old name of RB_FL_UNSET_RAW.
Definition fl_type.h:133
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define FL_TEST_RAW
Old name of RB_FL_TEST_RAW.
Definition fl_type.h:131
#define FL_SET
Old name of RB_FL_SET.
Definition fl_type.h:128
#define LONG2NUM
Old name of RB_LONG2NUM.
Definition long.h:50
#define Qtrue
Old name of RUBY_Qtrue.
#define INT2NUM
Old name of RB_INT2NUM.
Definition int.h:43
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define NIL_P
Old name of RB_NIL_P.
#define Check_TypedStruct(v, t)
Old name of rb_check_typeddata.
Definition rtypeddata.h:106
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition long.h:51
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define FL_SET_RAW
Old name of RB_FL_SET_RAW.
Definition fl_type.h:129
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
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1431
VALUE rb_eStopIteration
StopIteration exception.
Definition enumerator.c:181
VALUE rb_ensure(VALUE(*b_proc)(VALUE), VALUE data1, VALUE(*e_proc)(VALUE), VALUE data2)
An equivalent to ensure clause.
Definition eval.c:1178
VALUE rb_eThreadError
ThreadError exception.
Definition eval.c:1045
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:264
VALUE rb_cThread
Thread class.
Definition vm.c:671
double rb_num2dbl(VALUE num)
Converts an instance of rb_cNumeric into C's double.
Definition object.c:3829
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
Definition object.c:176
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition gc.h:603
VALUE rb_ary_concat(VALUE lhs, VALUE rhs)
Destructively appends the contents of latter into the end of former.
VALUE rb_ary_shift(VALUE ary)
Destructively deletes an element from the beginning of the passed array and returns what was deleted.
VALUE rb_ary_hidden_new(long capa)
Allocates a hidden (no class) empty array.
VALUE rb_ary_clear(VALUE ary)
Destructively removes everything form an array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
void rb_provide(const char *feature)
Declares that the given feature is already provided by someone else.
Definition load.c:695
VALUE rb_mutex_new(void)
Creates a mutex.
VALUE rb_mutex_trylock(VALUE mutex)
Attempts to lock the mutex, without waiting for other threads to unlock it.
VALUE rb_mutex_locked_p(VALUE mutex)
Queries if there are any threads that holds the lock.
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.
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.
VALUE rb_mutex_unlock(VALUE mutex)
Releases the mutex.
VALUE rb_mutex_lock(VALUE mutex)
Attempts to lock the mutex.
struct timeval rb_time_interval(VALUE num)
Creates a "time interval".
Definition time.c:2950
void rb_const_set(VALUE space, ID name, VALUE val)
Names a constant.
Definition variable.c:3983
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
char * ptr
Pointer to the underlying memory region, of at least capa bytes.
Definition io.h:2
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:51
#define RUBY_TYPED_DEFAULT_FREE
This is a value you can set to rb_data_type_struct::dfree.
Definition rtypeddata.h:80
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
Definition rtypeddata.h:649
struct rb_data_type_struct rb_data_type_t
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:205
#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
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
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
VALUE rb_fiber_scheduler_kernel_sleep(VALUE scheduler, VALUE duration)
Non-blocking sleep.
Definition scheduler.c:543
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
#define RTEST
This is an old name of RB_TEST.
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
void ruby_xfree(void *ptr)
Deallocates a storage instance.
Definition gc.c:5283