Ruby: thread_sync.c Source File

Ruby 3.3.6p108 (2024-11-05 revision 75015d4c1f6965b5e85e96fb309f1f2129f933c0)

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