61#undef __USE_FORTIFY_LEVEL
62#define __USE_FORTIFY_LEVEL 0
66#include "ruby/internal/config.h"
73#define TH_SCHED(th) (&(th)->ractor->threads.sched)
75#include "eval_intern.h"
78#include "internal/class.h"
79#include "internal/cont.h"
80#include "internal/error.h"
81#include "internal/gc.h"
82#include "internal/hash.h"
83#include "internal/io.h"
84#include "internal/object.h"
85#include "internal/proc.h"
87#include "internal/signal.h"
88#include "internal/thread.h"
89#include "internal/time.h"
90#include "internal/warnings.h"
98#include "ractor_core.h"
102#ifndef USE_NATIVE_THREAD_PRIORITY
103#define USE_NATIVE_THREAD_PRIORITY 0
104#define RUBY_THREAD_PRIORITY_MAX 3
105#define RUBY_THREAD_PRIORITY_MIN -3
108static VALUE rb_cThreadShield;
109static VALUE cThGroup;
111static VALUE sym_immediate;
112static VALUE sym_on_blocking;
113static VALUE sym_never;
115static uint32_t thread_default_quantum_ms = 100;
117#define THREAD_LOCAL_STORAGE_INITIALISED FL_USER13
118#define THREAD_LOCAL_STORAGE_INITIALISED_P(th) RB_FL_TEST_RAW((th), THREAD_LOCAL_STORAGE_INITIALISED)
121rb_thread_local_storage(
VALUE thread)
123 if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
131 SLEEP_DEADLOCKABLE = 0x01,
132 SLEEP_SPURIOUS_CHECK = 0x02,
133 SLEEP_ALLOW_SPURIOUS = 0x04,
134 SLEEP_NO_CHECKINTS = 0x08,
137static void sleep_forever(
rb_thread_t *th,
unsigned int fl);
138static int sleep_hrtime(
rb_thread_t *, rb_hrtime_t,
unsigned int fl);
140static void rb_thread_sleep_deadly_allow_spurious_wakeup(
VALUE blocker,
VALUE timeout, rb_hrtime_t end);
143static int rb_threadptr_pending_interrupt_empty_p(
const rb_thread_t *th);
144static const char *thread_status_name(
rb_thread_t *th,
int detail);
145static int hrtime_update_expire(rb_hrtime_t *,
const rb_hrtime_t);
146NORETURN(
static void async_bug_fd(
const char *mesg,
int errno_arg,
int fd));
147MAYBE_UNUSED(
static int consume_communication_pipe(
int fd));
149static volatile int system_working = 1;
150static rb_internal_thread_specific_key_t specific_key_count;
153 struct ccan_list_node wfd_node;
161#define THREAD_SYSTEM_DEPENDENT_IMPLEMENTATION
164 enum rb_thread_status prev_status;
168static void unblock_function_clear(
rb_thread_t *th);
174#define THREAD_BLOCKING_BEGIN(th) do { \
175 struct rb_thread_sched * const sched = TH_SCHED(th); \
176 RB_VM_SAVE_MACHINE_CONTEXT(th); \
177 thread_sched_to_waiting((sched), (th));
179#define THREAD_BLOCKING_END(th) \
180 thread_sched_to_running((sched), (th)); \
181 rb_ractor_thread_switch(th->ractor, th); \
185#ifdef HAVE_BUILTIN___BUILTIN_CHOOSE_EXPR_CONSTANT_P
186#define only_if_constant(expr, notconst) __builtin_choose_expr(__builtin_constant_p(expr), (expr), (notconst))
188#define only_if_constant(expr, notconst) (__builtin_constant_p(expr) ? (expr) : (notconst))
191#define only_if_constant(expr, notconst) notconst
193#define BLOCKING_REGION(th, exec, ubf, ubfarg, fail_if_interrupted) do { \
194 struct rb_blocking_region_buffer __region; \
195 if (blocking_region_begin(th, &__region, (ubf), (ubfarg), fail_if_interrupted) || \
197 !only_if_constant(fail_if_interrupted, TRUE)) { \
200 RB_VM_SAVE_MACHINE_CONTEXT(th); \
201 thread_sched_to_waiting(TH_SCHED(th), th); \
203 blocking_region_end(th, &__region); \
211#define RUBY_VM_CHECK_INTS_BLOCKING(ec) vm_check_ints_blocking(ec)
217 if (LIKELY(rb_threadptr_pending_interrupt_empty_p(th))) {
218 if (LIKELY(!RUBY_VM_INTERRUPTED_ANY(ec)))
return FALSE;
221 th->pending_interrupt_queue_checked = 0;
222 RUBY_VM_SET_INTERRUPT(ec);
224 return rb_threadptr_execute_interrupts(th, 1);
230 return vm_check_ints_blocking(ec);
238#if defined(HAVE_POLL)
239# if defined(__linux__)
242# if defined(__FreeBSD_version) && __FreeBSD_version >= 1100000
245# define POLLERR_SET (POLLHUP | POLLERR)
250timeout_prepare(rb_hrtime_t **to, rb_hrtime_t *rel, rb_hrtime_t *end,
254 *rel = rb_timeval2hrtime(timeout);
255 *end = rb_hrtime_add(rb_hrtime_now(), *rel);
263MAYBE_UNUSED(NOINLINE(
static int thread_start_func_2(
rb_thread_t *th,
VALUE *stack_start)));
264MAYBE_UNUSED(
static bool th_has_dedicated_nt(
const rb_thread_t *th));
265MAYBE_UNUSED(
static int waitfd_to_waiting_flag(
int wfd_event));
267#include THREAD_IMPL_SRC
274#ifndef BUSY_WAIT_SIGNALS
275# define BUSY_WAIT_SIGNALS (0)
279# define USE_EVENTFD (0)
282#include "thread_sync.c"
312 if (fail_if_interrupted) {
313 if (RUBY_VM_INTERRUPTED_ANY(th->ec)) {
318 RUBY_VM_CHECK_INTS(th->ec);
322 }
while (!th->ec->raised_flag && RUBY_VM_INTERRUPTED_ANY(th->ec) &&
325 VM_ASSERT(th->unblock.func == NULL);
327 th->unblock.func = func;
328 th->unblock.arg = arg;
338 th->unblock.func = 0;
343threadptr_interrupt_locked(
rb_thread_t *th,
bool trap)
347 RUBY_DEBUG_LOG(
"th:%u trap:%d", rb_th_serial(th), trap);
350 RUBY_VM_SET_TRAP_INTERRUPT(th->ec);
353 RUBY_VM_SET_INTERRUPT(th->ec);
356 if (th->unblock.func != NULL) {
357 (th->unblock.func)(th->unblock.arg);
369 threadptr_interrupt_locked(th, trap);
377 RUBY_DEBUG_LOG(
"th:%u", rb_th_serial(th));
378 threadptr_interrupt(th,
false);
384 threadptr_interrupt(th,
true);
392 ccan_list_for_each(&r->threads.set, th, lt_node) {
393 if (th != main_thread) {
394 RUBY_DEBUG_LOG(
"terminate start th:%u status:%s", rb_th_serial(th), thread_status_name(th, TRUE));
396 rb_threadptr_pending_interrupt_enque(th, RUBY_FATAL_THREAD_TERMINATED);
397 rb_threadptr_interrupt(th);
399 RUBY_DEBUG_LOG(
"terminate done th:%u status:%s", rb_th_serial(th), thread_status_name(th, TRUE));
402 RUBY_DEBUG_LOG(
"main thread th:%u", rb_th_serial(th));
410 while (thread->join_list) {
414 thread->join_list = join_list->next;
418 if (target_thread->scheduler !=
Qnil && join_list->fiber) {
422 rb_threadptr_interrupt(target_thread);
424 switch (target_thread->status) {
426 case THREAD_STOPPED_FOREVER:
427 target_thread->status = THREAD_RUNNABLE;
437rb_threadptr_unlock_all_locking_mutexes(
rb_thread_t *th)
439 while (th->keeping_mutexes) {
441 th->keeping_mutexes = mutex->next_mutex;
445 const char *error_message = rb_mutex_unlock_th(mutex, th, mutex->fiber);
446 if (error_message) rb_bug(
"invalid keeping_mutexes: %s", error_message);
455 volatile int sleeping = 0;
457 if (cr->threads.main != th) {
458 rb_bug(
"rb_thread_terminate_all: called by child thread (%p, %p)",
459 (
void *)cr->threads.main, (
void *)th);
463 rb_threadptr_unlock_all_locking_mutexes(th);
466 if (EC_EXEC_TAG() == TAG_NONE) {
468 RUBY_DEBUG_LOG(
"th:%u", rb_th_serial(th));
470 terminate_all(cr, th);
472 while (rb_ractor_living_thread_num(cr) > 1) {
473 rb_hrtime_t rel = RB_HRTIME_PER_SEC;
479 native_sleep(th, &rel);
480 RUBY_VM_CHECK_INTS_BLOCKING(ec);
498void rb_threadptr_root_fiber_terminate(
rb_thread_t *th);
499static void threadptr_interrupt_exec_cleanup(
rb_thread_t *th);
502thread_cleanup_func_before_exec(
void *th_ptr)
505 th->status = THREAD_KILLED;
508 th->ec->machine.stack_start = th->ec->machine.stack_end = NULL;
510 threadptr_interrupt_exec_cleanup(th);
511 rb_threadptr_root_fiber_terminate(th);
515thread_cleanup_func(
void *th_ptr,
int atfork)
519 th->locking_mutex =
Qfalse;
520 thread_cleanup_func_before_exec(th_ptr);
539ruby_thread_init_stack(
rb_thread_t *th,
void *local_in_parent_frame)
541 native_thread_init_stack(th, local_in_parent_frame);
545rb_vm_proc_local_ep(
VALUE proc)
547 const VALUE *ep = vm_proc_ep(proc);
550 return rb_vm_ep_local_ep(ep);
559 int argc,
const VALUE *argv,
int kw_splat,
VALUE passed_block_handler);
564 VALUE args = th->invoke_arg.proc.args;
565 const VALUE *args_ptr;
567 VALUE procval = th->invoke_arg.proc.proc;
569 GetProcPtr(procval, proc);
571 th->ec->errinfo =
Qnil;
572 th->ec->root_lep = rb_vm_proc_local_ep(procval);
573 th->ec->root_svar =
Qfalse;
575 vm_check_ints_blocking(th->ec);
577 if (th->invoke_type == thread_invoke_type_ractor_proc) {
578 VALUE self = rb_ractor_self(th->ractor);
579 th->thgroup = th->ractor->thgroup_default =
rb_obj_alloc(cThGroup);
584 rb_ractor_receive_parameters(th->ec, th->ractor, args_len, (
VALUE *)args_ptr);
585 vm_check_ints_blocking(th->ec);
587 return rb_vm_invoke_proc_with_self(
590 th->invoke_arg.proc.kw_splat,
591 VM_BLOCK_HANDLER_NONE
600 th->invoke_arg.proc.args =
Qnil;
606 vm_check_ints_blocking(th->ec);
608 return rb_vm_invoke_proc(
611 th->invoke_arg.proc.kw_splat,
612 VM_BLOCK_HANDLER_NONE
620 native_set_thread_name(th);
623 switch (th->invoke_type) {
624 case thread_invoke_type_proc:
625 result = thread_do_start_proc(th);
628 case thread_invoke_type_ractor_proc:
629 result = thread_do_start_proc(th);
630 rb_ractor_atexit(th->ec, result);
633 case thread_invoke_type_func:
634 result = (*th->invoke_arg.func.func)(th->invoke_arg.func.arg);
637 case thread_invoke_type_none:
638 rb_bug(
"unreachable");
649 RUBY_DEBUG_LOG(
"th:%u", rb_th_serial(th));
650 VM_ASSERT(th != th->vm->ractor.main_thread);
652 enum ruby_tag_type state;
654 rb_thread_t *ractor_main_th = th->ractor->threads.main;
657 if (rb_ractor_status_p(th->ractor, ractor_blocking)) {
660 rb_vm_ractor_blocking_cnt_dec(th->vm, th->ractor, __FILE__, __LINE__);
662 r->r_stdin = rb_io_prep_stdin();
663 r->r_stdout = rb_io_prep_stdout();
664 r->r_stderr = rb_io_prep_stderr();
670 VM_ASSERT(UNDEF_P(th->value));
672 int fiber_scheduler_closed = 0, event_thread_end_hooked = 0;
677 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
680 result = thread_do_start(th);
683 if (!fiber_scheduler_closed) {
684 fiber_scheduler_closed = 1;
688 if (!event_thread_end_hooked) {
689 event_thread_end_hooked = 1;
693 if (state == TAG_NONE) {
698 errinfo = th->ec->errinfo;
700 VALUE exc = rb_vm_make_jump_tag_but_local_jump(state,
Qundef);
701 if (!
NIL_P(exc)) errinfo = exc;
703 if (state == TAG_FATAL) {
704 if (th->invoke_type == thread_invoke_type_ractor_proc) {
705 rb_ractor_atexit(th->ec,
Qnil);
713 if (th->report_on_exception) {
714 VALUE mesg = rb_thread_to_s(th->self);
715 rb_str_cat_cstr(mesg,
" terminated with exception (report_on_exception is true):\n");
716 rb_write_error_str(mesg);
717 rb_ec_error_print(th->ec, errinfo);
720 if (th->invoke_type == thread_invoke_type_ractor_proc) {
721 rb_ractor_atexit_exception(th->ec);
724 if (th->vm->thread_abort_on_exception ||
736 VM_ASSERT(!UNDEF_P(th->value));
738 rb_threadptr_join_list_wakeup(th);
739 rb_threadptr_unlock_all_locking_mutexes(th);
741 if (th->invoke_type == thread_invoke_type_ractor_proc) {
742 rb_thread_terminate_all(th);
743 rb_ractor_teardown(th->ec);
746 th->status = THREAD_KILLED;
747 RUBY_DEBUG_LOG(
"killed th:%u", rb_th_serial(th));
749 if (th->vm->ractor.main_thread == th) {
755 rb_threadptr_raise(ractor_main_th, 1, &errinfo);
760 rb_ec_clear_current_thread_trace_func(th->ec);
763 if (th->locking_mutex !=
Qfalse) {
764 rb_bug(
"thread_start_func_2: locking_mutex must not be set (%p:%"PRIxVALUE
")",
765 (
void *)th, th->locking_mutex);
768 if (ractor_main_th->status == THREAD_KILLED &&
769 th->ractor->threads.cnt <= 2 ) {
771 rb_threadptr_interrupt(ractor_main_th);
774 rb_check_deadlock(th->ractor);
776 rb_fiber_close(th->ec->fiber_ptr);
778 thread_cleanup_func(th, FALSE);
779 VM_ASSERT(th->ec->vm_stack == NULL);
781 if (th->invoke_type == thread_invoke_type_ractor_proc) {
785 thread_sched_to_dead(TH_SCHED(th), th);
786 rb_ractor_living_threads_remove(th->ractor, th);
789 rb_ractor_living_threads_remove(th->ractor, th);
790 thread_sched_to_dead(TH_SCHED(th), th);
797 enum thread_invoke_type type;
810static void thread_specific_storage_alloc(
rb_thread_t *th);
816 rb_thread_t *th = rb_thread_ptr(thval), *current_th = rb_ec_thread_ptr(ec);
819 thread_specific_storage_alloc(th);
823 "can't start a new thread (frozen ThreadGroup)");
826 rb_fiber_inherit_storage(ec, th->ec->fiber_ptr);
828 switch (params->type) {
829 case thread_invoke_type_proc:
830 th->invoke_type = thread_invoke_type_proc;
831 th->invoke_arg.proc.args = params->args;
832 th->invoke_arg.proc.proc = params->proc;
836 case thread_invoke_type_ractor_proc:
837#if RACTOR_CHECK_MODE > 0
838 rb_ractor_setup_belonging_to(thval, rb_ractor_id(params->g));
840 th->invoke_type = thread_invoke_type_ractor_proc;
841 th->ractor = params->g;
842 th->ractor->threads.main = th;
843 th->invoke_arg.proc.proc = rb_proc_isolate_bang(params->proc);
846 rb_ractor_send_parameters(ec, params->g, params->args);
849 case thread_invoke_type_func:
850 th->invoke_type = thread_invoke_type_func;
851 th->invoke_arg.func.func = params->fn;
852 th->invoke_arg.func.arg = (
void *)params->args;
856 rb_bug(
"unreachable");
859 th->priority = current_th->priority;
860 th->thgroup = current_th->thgroup;
862 th->pending_interrupt_queue = rb_ary_hidden_new(0);
863 th->pending_interrupt_queue_checked = 0;
864 th->pending_interrupt_mask_stack = rb_ary_dup(current_th->pending_interrupt_mask_stack);
865 RBASIC_CLEAR_CLASS(th->pending_interrupt_mask_stack);
869 RUBY_DEBUG_LOG(
"r:%u th:%u", rb_ractor_id(th->ractor), rb_th_serial(th));
871 rb_ractor_living_threads_insert(th->ractor, th);
874 err = native_thread_create(th);
876 th->status = THREAD_KILLED;
877 rb_ractor_living_threads_remove(th->ractor, th);
883#define threadptr_initialized(th) ((th)->invoke_type != thread_invoke_type_none)
906thread_s_new(
int argc,
VALUE *argv,
VALUE klass)
909 VALUE thread = rb_thread_alloc(klass);
911 if (GET_RACTOR()->threads.main->status == THREAD_KILLED) {
916 th = rb_thread_ptr(thread);
917 if (!threadptr_initialized(th)) {
918 rb_raise(
rb_eThreadError,
"uninitialized thread - check '%"PRIsVALUE
"#initialize'",
938 .type = thread_invoke_type_proc,
942 return thread_create_core(rb_thread_alloc(klass), ¶ms);
948 if (th->invoke_type == thread_invoke_type_proc) {
949 return rb_proc_location(th->invoke_arg.proc.proc);
965 else if (th->invoke_type != thread_invoke_type_none) {
966 VALUE loc = threadptr_invoke_proc_location(th);
969 "already initialized thread - %"PRIsVALUE
":%"PRIsVALUE,
978 .type = thread_invoke_type_proc,
982 return thread_create_core(thread, ¶ms);
990 .type = thread_invoke_type_func,
994 return thread_create_core(rb_thread_alloc(
rb_cThread), ¶ms);
1001 .type = thread_invoke_type_ractor_proc,
1006 return thread_create_core(rb_thread_alloc(
rb_cThread), ¶ms);;
1018remove_from_join_list(
VALUE arg)
1023 if (target_thread->status != THREAD_KILLED) {
1026 while (*join_list) {
1027 if (*join_list == p->waiter) {
1028 *join_list = (*join_list)->next;
1032 join_list = &(*join_list)->next;
1042 return th->status == THREAD_KILLED || !UNDEF_P(th->value);
1046thread_join_sleep(
VALUE arg)
1049 rb_thread_t *target_th = p->target, *th = p->waiter->thread;
1050 rb_hrtime_t end = 0, *limit = p->limit;
1053 end = rb_hrtime_add(*limit, rb_hrtime_now());
1056 while (!thread_finished(target_th)) {
1059 if (scheduler !=
Qnil) {
1062 if (thread_finished(target_th))
break;
1067 sleep_forever(th, SLEEP_DEADLOCKABLE | SLEEP_ALLOW_SPURIOUS | SLEEP_NO_CHECKINTS);
1070 if (hrtime_update_expire(limit, end)) {
1071 RUBY_DEBUG_LOG(
"timeout target_th:%u", rb_th_serial(target_th));
1074 th->status = THREAD_STOPPED;
1075 native_sleep(th, limit);
1077 RUBY_VM_CHECK_INTS_BLOCKING(th->ec);
1078 th->status = THREAD_RUNNABLE;
1080 RUBY_DEBUG_LOG(
"interrupted target_th:%u status:%s", rb_th_serial(target_th), thread_status_name(target_th, TRUE));
1093 if (th == target_th) {
1094 rb_raise(
rb_eThreadError,
"Target thread must not be current thread");
1097 if (th->ractor->threads.main == target_th) {
1101 RUBY_DEBUG_LOG(
"target_th:%u status:%s", rb_th_serial(target_th), thread_status_name(target_th, TRUE));
1103 if (target_th->status != THREAD_KILLED) {
1105 waiter.next = target_th->join_list;
1107 waiter.fiber = rb_fiberptr_blocking(fiber) ? NULL : fiber;
1108 target_th->join_list = &waiter;
1111 arg.waiter = &waiter;
1112 arg.target = target_th;
1113 arg.timeout = timeout;
1121 RUBY_DEBUG_LOG(
"success target_th:%u status:%s", rb_th_serial(target_th), thread_status_name(target_th, TRUE));
1123 if (target_th->ec->errinfo !=
Qnil) {
1124 VALUE err = target_th->ec->errinfo;
1129 RUBY_DEBUG_LOG(
"terminated target_th:%u status:%s", rb_th_serial(target_th), thread_status_name(target_th, TRUE));
1134 rb_bug(
"thread_join: Fixnum (%d) should not reach here.",
FIX2INT(err));
1137 else if (THROW_DATA_P(target_th->ec->errinfo)) {
1138 rb_bug(
"thread_join: THROW_DATA should not reach here.");
1145 return target_th->self;
1188thread_join_m(
int argc,
VALUE *argv,
VALUE self)
1191 rb_hrtime_t rel = 0, *limit = 0;
1202 if (
NIL_P(timeout)) {
1206 rel = rb_sec2hrtime(NUM2TIMET(timeout));
1210 limit = double2hrtime(&rel,
rb_num2dbl(timeout));
1213 return thread_join(rb_thread_ptr(self), timeout, limit);
1231thread_value(
VALUE self)
1234 thread_join(th,
Qnil, 0);
1235 if (UNDEF_P(th->value)) {
1249#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
1250 if (clock_gettime(CLOCK_MONOTONIC, ts) == 0)
1260NOINLINE(rb_hrtime_t rb_hrtime_now(
void));
1267 return rb_timespec2hrtime(&ts);
1274COMPILER_WARNING_PUSH
1275#if defined(__GNUC__) && __GNUC__ == 7 && __GNUC_MINOR__ <= 3
1276COMPILER_WARNING_IGNORED(-Wmaybe-uninitialized)
1279#define PRIu64 PRI_64_PREFIX "u"
1287hrtime_update_expire(rb_hrtime_t *timeout,
const rb_hrtime_t end)
1289 rb_hrtime_t now = rb_hrtime_now();
1291 if (now > end)
return 1;
1293 RUBY_DEBUG_LOG(
"%"PRIu64
" > %"PRIu64
"", (uint64_t)end, (uint64_t)now);
1295 *timeout = end - now;
1301sleep_hrtime(
rb_thread_t *th, rb_hrtime_t rel,
unsigned int fl)
1303 enum rb_thread_status prev_status = th->status;
1305 rb_hrtime_t end = rb_hrtime_add(rb_hrtime_now(), rel);
1307 th->status = THREAD_STOPPED;
1308 RUBY_VM_CHECK_INTS_BLOCKING(th->ec);
1309 while (th->status == THREAD_STOPPED) {
1310 native_sleep(th, &rel);
1311 woke = vm_check_ints_blocking(th->ec);
1312 if (woke && !(fl & SLEEP_SPURIOUS_CHECK))
1314 if (hrtime_update_expire(&rel, end))
1318 th->status = prev_status;
1323sleep_hrtime_until(
rb_thread_t *th, rb_hrtime_t end,
unsigned int fl)
1325 enum rb_thread_status prev_status = th->status;
1327 rb_hrtime_t rel = rb_hrtime_sub(end, rb_hrtime_now());
1329 th->status = THREAD_STOPPED;
1330 RUBY_VM_CHECK_INTS_BLOCKING(th->ec);
1331 while (th->status == THREAD_STOPPED) {
1332 native_sleep(th, &rel);
1333 woke = vm_check_ints_blocking(th->ec);
1334 if (woke && !(fl & SLEEP_SPURIOUS_CHECK))
1336 if (hrtime_update_expire(&rel, end))
1340 th->status = prev_status;
1347 enum rb_thread_status prev_status = th->status;
1348 enum rb_thread_status status;
1351 status = fl & SLEEP_DEADLOCKABLE ? THREAD_STOPPED_FOREVER : THREAD_STOPPED;
1352 th->status = status;
1354 if (!(fl & SLEEP_NO_CHECKINTS)) RUBY_VM_CHECK_INTS_BLOCKING(th->ec);
1356 while (th->status == status) {
1357 if (fl & SLEEP_DEADLOCKABLE) {
1358 rb_ractor_sleeper_threads_inc(th->ractor);
1359 rb_check_deadlock(th->ractor);
1362 native_sleep(th, 0);
1364 if (fl & SLEEP_DEADLOCKABLE) {
1365 rb_ractor_sleeper_threads_dec(th->ractor);
1367 if (fl & SLEEP_ALLOW_SPURIOUS) {
1371 woke = vm_check_ints_blocking(th->ec);
1373 if (woke && !(fl & SLEEP_SPURIOUS_CHECK)) {
1377 th->status = prev_status;
1383 RUBY_DEBUG_LOG(
"forever");
1384 sleep_forever(GET_THREAD(), SLEEP_SPURIOUS_CHECK);
1390 RUBY_DEBUG_LOG(
"deadly");
1391 sleep_forever(GET_THREAD(), SLEEP_DEADLOCKABLE|SLEEP_SPURIOUS_CHECK);
1395rb_thread_sleep_deadly_allow_spurious_wakeup(
VALUE blocker,
VALUE timeout, rb_hrtime_t end)
1398 if (scheduler !=
Qnil) {
1402 RUBY_DEBUG_LOG(
"...");
1404 sleep_hrtime_until(GET_THREAD(), end, SLEEP_SPURIOUS_CHECK);
1407 sleep_forever(GET_THREAD(), SLEEP_DEADLOCKABLE);
1417 sleep_hrtime(th, rb_timeval2hrtime(&time), SLEEP_SPURIOUS_CHECK);
1423 RUBY_VM_CHECK_INTS_BLOCKING(ec);
1436 rb_ec_check_ints(GET_EC());
1444rb_thread_check_trap_pending(
void)
1446 return rb_signal_buff_size() != 0;
1453 return (
int)RUBY_VM_INTERRUPTED(rb_thread_ptr(thval)->ec);
1463rb_thread_schedule_limits(uint32_t limits_us)
1467 RUBY_DEBUG_LOG(
"us:%u", (
unsigned int)limits_us);
1469 if (th->running_time_us >= limits_us) {
1470 RUBY_DEBUG_LOG(
"switch %s",
"start");
1472 RB_VM_SAVE_MACHINE_CONTEXT(th);
1473 thread_sched_yield(TH_SCHED(th), th);
1474 rb_ractor_thread_switch(th->ractor, th);
1476 RUBY_DEBUG_LOG(
"switch %s",
"done");
1484 rb_thread_schedule_limits(0);
1485 RUBY_VM_CHECK_INTS(GET_EC());
1494#ifdef RUBY_ASSERT_CRITICAL_SECTION
1495 VM_ASSERT(ruby_assert_critical_section_entered == 0);
1497 VM_ASSERT(th == GET_THREAD());
1499 region->prev_status = th->status;
1500 if (unblock_function_set(th, ubf, arg, fail_if_interrupted)) {
1501 th->blocking_region_buffer = region;
1502 th->status = THREAD_STOPPED;
1503 rb_ractor_blocking_threads_inc(th->ractor, __FILE__, __LINE__);
1505 RUBY_DEBUG_LOG(
"thread_id:%p", (
void *)th->nt->thread_id);
1517 unblock_function_clear(th);
1519 unregister_ubf_list(th);
1521 thread_sched_to_running(TH_SCHED(th), th);
1522 rb_ractor_thread_switch(th->ractor, th);
1524 th->blocking_region_buffer = 0;
1525 rb_ractor_blocking_threads_dec(th->ractor, __FILE__, __LINE__);
1526 if (th->status == THREAD_STOPPED) {
1527 th->status = region->prev_status;
1530 RUBY_DEBUG_LOG(
"end");
1534 VM_ASSERT(th == GET_THREAD());
1539rb_nogvl(
void *(*func)(
void *),
void *data1,
1545 if (scheduler !=
Qnil) {
1550 if (!UNDEF_P(result)) {
1551 rb_errno_set(state.saved_errno);
1552 return state.result;
1560 rb_vm_t *vm = rb_ec_vm_ptr(ec);
1561 bool is_main_thread = vm->ractor.main_thread == th;
1562 int saved_errno = 0;
1568 else if (ubf && rb_ractor_living_thread_num(th->ractor) == 1 && is_main_thread) {
1570 vm->ubf_async_safe = 1;
1574 rb_vm_t *
volatile saved_vm = vm;
1575 BLOCKING_REGION(th, {
1577 saved_errno = rb_errno();
1581 if (is_main_thread) vm->ubf_async_safe = 0;
1584 RUBY_VM_CHECK_INTS_BLOCKING(ec);
1587 rb_errno_set(saved_errno);
1688 return rb_nogvl(func, data1, ubf, data2, 0);
1692waitfd_to_waiting_flag(
int wfd_event)
1694 return wfd_event << 1;
1706 ccan_list_add(&th->vm->waiting_fds, &wfd->wfd_node);
1712thread_io_wake_pending_closer(
struct waiting_fd *wfd)
1714 bool has_waiter = wfd->busy &&
RB_TEST(wfd->busy->wakeup_mutex);
1723 ccan_list_del(&wfd->wfd_node);
1727 rb_thread_t *th = rb_thread_ptr(wfd->busy->closing_thread);
1728 if (th->scheduler !=
Qnil) {
1741#if defined(USE_MN_THREADS) && USE_MN_THREADS
1742 return !th_has_dedicated_nt(th) && (events || timeout) && th->blocking;
1750thread_io_wait_events(
rb_thread_t *th,
int fd,
int events,
const struct timeval *timeout)
1752#if defined(USE_MN_THREADS) && USE_MN_THREADS
1753 if (thread_io_mn_schedulable(th, events, timeout)) {
1754 rb_hrtime_t rel, *prel;
1757 rel = rb_timeval2hrtime(timeout);
1764 VM_ASSERT(prel || (events & (RB_WAITFD_IN | RB_WAITFD_OUT)));
1766 if (thread_sched_wait_events(TH_SCHED(th), th, fd, waitfd_to_waiting_flag(events), prel)) {
1780blocking_call_retryable_p(
int r,
int eno)
1782 if (r != -1)
return false;
1786#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
1796rb_thread_mn_schedulable(
VALUE thval)
1799 return th->mn_schedulable;
1803rb_thread_io_blocking_call(
struct rb_io* io, rb_blocking_function_t *func,
void *data1,
int events)
1808 RUBY_DEBUG_LOG(
"th:%u fd:%d ev:%d", rb_th_serial(th), io->
fd, events);
1812 volatile int saved_errno = 0;
1813 enum ruby_tag_type state;
1814 volatile bool prev_mn_schedulable = th->mn_schedulable;
1815 th->mn_schedulable = thread_io_mn_schedulable(th, events, NULL);
1828 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
1829 volatile enum ruby_tag_type saved_state = state;
1831 BLOCKING_REGION(th, {
1833 saved_errno =
errno;
1834 }, ubf_select, th, FALSE);
1836 th = rb_ec_thread_ptr(ec);
1838 blocking_call_retryable_p((
int)val, saved_errno) &&
1839 thread_io_wait_events(th, fd, events, NULL)) {
1840 RUBY_VM_CHECK_INTS_BLOCKING(ec);
1843 state = saved_state;
1847 th = rb_ec_thread_ptr(ec);
1848 th->mn_schedulable = prev_mn_schedulable;
1857 EC_JUMP_TAG(ec, state);
1860 RUBY_VM_CHECK_INTS_BLOCKING(ec);
1863 if (saved_errno == ETIMEDOUT) {
1867 errno = saved_errno;
1873rb_thread_io_blocking_region(
struct rb_io *io, rb_blocking_function_t *func,
void *data1)
1875 return rb_thread_io_blocking_call(io, func, data1, 0);
1920 fprintf(stderr,
"[BUG] rb_thread_call_with_gvl() is called by non-ruby thread\n");
1925 prev_unblock = th->unblock;
1928 rb_bug(
"rb_thread_call_with_gvl: called by a thread which has GVL.");
1931 blocking_region_end(th, brb);
1935 int released = blocking_region_begin(th, brb, prev_unblock.func, prev_unblock.arg, FALSE);
1937 RB_VM_SAVE_MACHINE_CONTEXT(th);
1938 thread_sched_to_waiting(TH_SCHED(th), th);
1947ruby_thread_has_gvl_p(
void)
1951 if (th && th->blocking_region_buffer == 0) {
1968thread_s_pass(
VALUE klass)
1993rb_threadptr_pending_interrupt_clear(
rb_thread_t *th)
1995 rb_ary_clear(th->pending_interrupt_queue);
2001 rb_ary_push(th->pending_interrupt_queue, v);
2002 th->pending_interrupt_queue_checked = 0;
2006threadptr_check_pending_interrupt_queue(
rb_thread_t *th)
2008 if (!th->pending_interrupt_queue) {
2013enum handle_interrupt_timing {
2015 INTERRUPT_IMMEDIATE,
2016 INTERRUPT_ON_BLOCKING,
2020static enum handle_interrupt_timing
2023 if (sym == sym_immediate) {
2024 return INTERRUPT_IMMEDIATE;
2026 else if (sym == sym_on_blocking) {
2027 return INTERRUPT_ON_BLOCKING;
2029 else if (sym == sym_never) {
2030 return INTERRUPT_NEVER;
2037static enum handle_interrupt_timing
2041 long mask_stack_len =
RARRAY_LEN(th->pending_interrupt_mask_stack);
2046 for (i=0; i<mask_stack_len; i++) {
2047 mask = mask_stack[mask_stack_len-(i+1)];
2052 return rb_threadptr_pending_interrupt_from_symbol(th, mask);
2064 klass =
RBASIC(mod)->klass;
2066 else if (mod != RCLASS_ORIGIN(mod)) {
2070 if ((sym = rb_hash_aref(mask, klass)) !=
Qnil) {
2071 return rb_threadptr_pending_interrupt_from_symbol(th, sym);
2076 return INTERRUPT_NONE;
2080rb_threadptr_pending_interrupt_empty_p(
const rb_thread_t *th)
2082 return RARRAY_LEN(th->pending_interrupt_queue) == 0;
2089 for (i=0; i<
RARRAY_LEN(th->pending_interrupt_queue); i++) {
2099rb_threadptr_pending_interrupt_deque(
rb_thread_t *th,
enum handle_interrupt_timing timing)
2104 for (i=0; i<
RARRAY_LEN(th->pending_interrupt_queue); i++) {
2107 enum handle_interrupt_timing mask_timing = rb_threadptr_pending_interrupt_check_mask(th,
CLASS_OF(err));
2109 switch (mask_timing) {
2110 case INTERRUPT_ON_BLOCKING:
2111 if (timing != INTERRUPT_ON_BLOCKING) {
2115 case INTERRUPT_NONE:
2116 case INTERRUPT_IMMEDIATE:
2117 rb_ary_delete_at(th->pending_interrupt_queue, i);
2119 case INTERRUPT_NEVER:
2124 th->pending_interrupt_queue_checked = 1;
2127 VALUE err = rb_ary_shift(th->pending_interrupt_queue);
2128 if (rb_threadptr_pending_interrupt_empty_p(th)) {
2129 th->pending_interrupt_queue_checked = 1;
2136threadptr_pending_interrupt_active_p(
rb_thread_t *th)
2143 if (th->pending_interrupt_queue_checked) {
2147 if (rb_threadptr_pending_interrupt_empty_p(th)) {
2159 if (val != sym_immediate && val != sym_on_blocking && val != sym_never) {
2160 rb_raise(rb_eArgError,
"unknown mask signature");
2168 if (
RTEST(*maskp)) {
2170 VALUE prev = *maskp;
2171 *maskp = rb_ident_hash_new();
2176 rb_hash_aset(*maskp, key, val);
2270rb_thread_s_handle_interrupt(
VALUE self,
VALUE mask_arg)
2276 enum ruby_tag_type state;
2279 rb_raise(rb_eArgError,
"block is needed.");
2282 mask_arg = rb_to_hash_type(mask_arg);
2284 if (
OBJ_FROZEN(mask_arg) && rb_hash_compare_by_id_p(mask_arg)) {
2290 if (UNDEF_P(mask)) {
2301 rb_ary_push(th->pending_interrupt_mask_stack, mask);
2302 if (!rb_threadptr_pending_interrupt_empty_p(th)) {
2303 th->pending_interrupt_queue_checked = 0;
2304 RUBY_VM_SET_INTERRUPT(th->ec);
2307 EC_PUSH_TAG(th->ec);
2308 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
2313 rb_ary_pop(th->pending_interrupt_mask_stack);
2314 if (!rb_threadptr_pending_interrupt_empty_p(th)) {
2315 th->pending_interrupt_queue_checked = 0;
2316 RUBY_VM_SET_INTERRUPT(th->ec);
2319 RUBY_VM_CHECK_INTS(th->ec);
2322 EC_JUMP_TAG(th->ec, state);
2339rb_thread_pending_interrupt_p(
int argc,
VALUE *argv,
VALUE target_thread)
2341 rb_thread_t *target_th = rb_thread_ptr(target_thread);
2343 if (!target_th->pending_interrupt_queue) {
2346 if (rb_threadptr_pending_interrupt_empty_p(target_th)) {
2350 VALUE err = argv[0];
2352 rb_raise(
rb_eTypeError,
"class or module required for rescue clause");
2354 return RBOOL(rb_threadptr_pending_interrupt_include_p(target_th, err));
2419rb_thread_s_pending_interrupt_p(
int argc,
VALUE *argv,
VALUE self)
2421 return rb_thread_pending_interrupt_p(argc, argv, GET_THREAD()->self);
2424NORETURN(
static void rb_threadptr_to_kill(
rb_thread_t *th));
2429 rb_threadptr_pending_interrupt_clear(th);
2430 th->status = THREAD_RUNNABLE;
2432 th->ec->errinfo =
INT2FIX(TAG_FATAL);
2433 EC_JUMP_TAG(th->ec, TAG_FATAL);
2444 interrupt = ec->interrupt_flag;
2445 old = ATOMIC_CAS(ec->interrupt_flag, interrupt, interrupt & ec->interrupt_mask);
2446 }
while (old != interrupt);
2447 return interrupt & (
rb_atomic_t)~ec->interrupt_mask;
2450static void threadptr_interrupt_exec_exec(
rb_thread_t *th);
2453rb_threadptr_execute_interrupts(
rb_thread_t *th,
int blocking_timing)
2456 int postponed_job_interrupt = 0;
2459 if (th->ec->raised_flag)
return ret;
2461 while ((interrupt = threadptr_get_interrupts(th)) != 0) {
2463 int timer_interrupt;
2464 int pending_interrupt;
2466 int terminate_interrupt;
2468 timer_interrupt = interrupt & TIMER_INTERRUPT_MASK;
2469 pending_interrupt = interrupt & PENDING_INTERRUPT_MASK;
2470 postponed_job_interrupt = interrupt & POSTPONED_JOB_INTERRUPT_MASK;
2471 trap_interrupt = interrupt & TRAP_INTERRUPT_MASK;
2472 terminate_interrupt = interrupt & TERMINATE_INTERRUPT_MASK;
2474 if (interrupt & VM_BARRIER_INTERRUPT_MASK) {
2479 if (postponed_job_interrupt) {
2480 rb_postponed_job_flush(th->vm);
2483 if (trap_interrupt) {
2485 if (th == th->vm->ractor.main_thread) {
2486 enum rb_thread_status prev_status = th->status;
2488 th->status = THREAD_RUNNABLE;
2490 while ((sig = rb_get_next_signal()) != 0) {
2491 ret |= rb_signal_exec(th, sig);
2494 th->status = prev_status;
2497 if (!ccan_list_empty(&th->interrupt_exec_tasks)) {
2498 enum rb_thread_status prev_status = th->status;
2500 th->status = THREAD_RUNNABLE;
2502 threadptr_interrupt_exec_exec(th);
2504 th->status = prev_status;
2509 if (pending_interrupt && threadptr_pending_interrupt_active_p(th)) {
2510 VALUE err = rb_threadptr_pending_interrupt_deque(th, blocking_timing ? INTERRUPT_ON_BLOCKING : INTERRUPT_NONE);
2511 RUBY_DEBUG_LOG(
"err:%"PRIdVALUE, err);
2517 else if (err == RUBY_FATAL_THREAD_KILLED ||
2518 err == RUBY_FATAL_THREAD_TERMINATED ||
2520 terminate_interrupt = 1;
2523 if (err == th->vm->special_exceptions[ruby_error_stream_closed]) {
2525 err = ruby_vm_special_exception_copy(err);
2528 if (th->status == THREAD_STOPPED ||
2529 th->status == THREAD_STOPPED_FOREVER)
2530 th->status = THREAD_RUNNABLE;
2535 if (terminate_interrupt) {
2536 rb_threadptr_to_kill(th);
2539 if (timer_interrupt) {
2540 uint32_t limits_us = thread_default_quantum_ms * 1000;
2542 if (th->priority > 0)
2543 limits_us <<= th->priority;
2545 limits_us >>= -th->priority;
2547 if (th->status == THREAD_RUNNABLE)
2548 th->running_time_us += 10 * 1000;
2550 VM_ASSERT(th->ec->cfp);
2554 rb_thread_schedule_limits(limits_us);
2561rb_thread_execute_interrupts(
VALUE thval)
2563 rb_threadptr_execute_interrupts(rb_thread_ptr(thval), 1);
2569 rb_threadptr_interrupt(th);
2577 if (rb_threadptr_dead(target_th)) {
2585 exc = rb_make_exception(argc, argv);
2590 if (rb_threadptr_dead(target_th)) {
2594 rb_ec_setup_exception(GET_EC(), exc,
Qundef);
2595 rb_threadptr_pending_interrupt_enque(target_th, exc);
2596 rb_threadptr_interrupt(target_th);
2601rb_threadptr_signal_raise(
rb_thread_t *th,
int sig)
2607 rb_threadptr_raise(th->vm->ractor.main_thread, 2, argv);
2619 rb_threadptr_raise(th->vm->ractor.main_thread, 2, argv);
2625 if (ec->raised_flag & RAISED_EXCEPTION) {
2628 ec->raised_flag |= RAISED_EXCEPTION;
2635 if (!(ec->raised_flag & RAISED_EXCEPTION)) {
2638 ec->raised_flag &= ~RAISED_EXCEPTION;
2645 rb_vm_t *vm = GET_THREAD()->vm;
2647 ccan_list_head_init(&busy->pending_fd_users);
2653 ccan_list_for_each_safe(&vm->waiting_fds, wfd, next, wfd_node) {
2654 if (wfd->fd == fd) {
2658 ccan_list_del(&wfd->wfd_node);
2659 ccan_list_add(&busy->pending_fd_users, &wfd->wfd_node);
2662 err = th->vm->special_exceptions[ruby_error_stream_closed];
2663 rb_threadptr_pending_interrupt_enque(th, err);
2664 rb_threadptr_interrupt(th);
2669 has_any = !ccan_list_empty(&busy->pending_fd_users);
2671 busy->closing_fiber = rb_fiber_current();
2672 wakeup_mutex =
Qnil;
2675 RBASIC_CLEAR_CLASS(wakeup_mutex);
2677 busy->wakeup_mutex = wakeup_mutex;
2691 if (!
RB_TEST(busy->wakeup_mutex)) {
2698 while (!ccan_list_empty(&busy->pending_fd_users)) {
2709 if (rb_notify_fd_close(fd, &busy)) {
2710 rb_notify_fd_close_wait(&busy);
2736thread_raise_m(
int argc,
VALUE *argv,
VALUE self)
2741 threadptr_check_pending_interrupt_queue(target_th);
2742 rb_threadptr_raise(target_th, argc, argv);
2745 if (current_th == target_th) {
2746 RUBY_VM_CHECK_INTS(target_th->ec);
2768 if (target_th->to_kill || target_th->status == THREAD_KILLED) {
2771 if (target_th == target_th->vm->ractor.main_thread) {
2775 RUBY_DEBUG_LOG(
"target_th:%u", rb_th_serial(target_th));
2777 if (target_th == GET_THREAD()) {
2779 rb_threadptr_to_kill(target_th);
2782 threadptr_check_pending_interrupt_queue(target_th);
2783 rb_threadptr_pending_interrupt_enque(target_th, RUBY_FATAL_THREAD_KILLED);
2784 rb_threadptr_interrupt(target_th);
2791rb_thread_to_be_killed(
VALUE thread)
2795 if (target_th->to_kill || target_th->status == THREAD_KILLED) {
2871 if (target_th->status == THREAD_KILLED)
return Qnil;
2873 rb_threadptr_ready(target_th);
2875 if (target_th->status == THREAD_STOPPED ||
2876 target_th->status == THREAD_STOPPED_FOREVER) {
2877 target_th->status = THREAD_RUNNABLE;
2919 "stopping only thread\n\tnote: use sleep to stop forever");
2952 return rb_ractor_thread_list();
2978 return rb_thread_list();
2984 return GET_THREAD()->self;
2997thread_s_current(
VALUE klass)
3005 return GET_RACTOR()->threads.main->self;
3016rb_thread_s_main(
VALUE klass)
3043rb_thread_s_abort_exc(
VALUE _)
3045 return RBOOL(GET_THREAD()->vm->thread_abort_on_exception);
3080rb_thread_s_abort_exc_set(
VALUE self,
VALUE val)
3082 GET_THREAD()->vm->thread_abort_on_exception =
RTEST(val);
3103rb_thread_abort_exc(
VALUE thread)
3105 return RBOOL(rb_thread_ptr(thread)->abort_on_exception);
3123rb_thread_abort_exc_set(
VALUE thread,
VALUE val)
3125 rb_thread_ptr(thread)->abort_on_exception =
RTEST(val);
3173rb_thread_s_report_exc(
VALUE _)
3175 return RBOOL(GET_THREAD()->vm->thread_report_on_exception);
3210rb_thread_s_report_exc_set(
VALUE self,
VALUE val)
3212 GET_THREAD()->vm->thread_report_on_exception =
RTEST(val);
3229rb_thread_s_ignore_deadlock(
VALUE _)
3231 return RBOOL(GET_THREAD()->vm->thread_ignore_deadlock);
3256rb_thread_s_ignore_deadlock_set(
VALUE self,
VALUE val)
3258 GET_THREAD()->vm->thread_ignore_deadlock =
RTEST(val);
3280rb_thread_report_exc(
VALUE thread)
3282 return RBOOL(rb_thread_ptr(thread)->report_on_exception);
3300rb_thread_report_exc_set(
VALUE thread,
VALUE val)
3302 rb_thread_ptr(thread)->report_on_exception =
RTEST(val);
3317rb_thread_group(
VALUE thread)
3319 return rb_thread_ptr(thread)->thgroup;
3325 switch (th->status) {
3326 case THREAD_RUNNABLE:
3327 return th->to_kill ?
"aborting" :
"run";
3328 case THREAD_STOPPED_FOREVER:
3329 if (detail)
return "sleep_forever";
3330 case THREAD_STOPPED:
3342 return th->status == THREAD_KILLED;
3378rb_thread_status(
VALUE thread)
3382 if (rb_threadptr_dead(target_th)) {
3383 if (!
NIL_P(target_th->ec->errinfo) &&
3384 !
FIXNUM_P(target_th->ec->errinfo)) {
3392 return rb_str_new2(thread_status_name(target_th, FALSE));
3412rb_thread_alive_p(
VALUE thread)
3414 return RBOOL(!thread_finished(rb_thread_ptr(thread)));
3432rb_thread_stop_p(
VALUE thread)
3436 if (rb_threadptr_dead(th)) {
3439 return RBOOL(th->status == THREAD_STOPPED || th->status == THREAD_STOPPED_FOREVER);
3450rb_thread_getname(
VALUE thread)
3452 return rb_thread_ptr(thread)->name;
3471 enc = rb_enc_get(name);
3472 if (!rb_enc_asciicompat(enc)) {
3473 rb_raise(rb_eArgError,
"ASCII incompatible encoding (%s)",
3478 target_th->name = name;
3479 if (threadptr_initialized(target_th) && target_th->has_dedicated_nt) {
3480 native_set_another_thread_name(target_th->nt->thread_id, name);
3485#if USE_NATIVE_THREAD_NATIVE_THREAD_ID
3509rb_thread_native_thread_id(
VALUE thread)
3512 if (rb_threadptr_dead(target_th))
return Qnil;
3513 return native_thread_native_thread_id(target_th);
3516# define rb_thread_native_thread_id rb_f_notimplement
3527rb_thread_to_s(
VALUE thread)
3534 status = thread_status_name(target_th, TRUE);
3535 str = rb_sprintf(
"#<%"PRIsVALUE
":%p", cname, (
void *)thread);
3536 if (!
NIL_P(target_th->name)) {
3537 rb_str_catf(str,
"@%"PRIsVALUE, target_th->name);
3539 if ((loc = threadptr_invoke_proc_location(target_th)) !=
Qnil) {
3540 rb_str_catf(str,
" %"PRIsVALUE
":%"PRIsVALUE,
3543 rb_str_catf(str,
" %s>", status);
3549#define recursive_key id__recursive_key__
3554 if (
id == recursive_key) {
3555 return th->ec->local_storage_recursive_hash;
3559 struct rb_id_table *local_storage = th->ec->local_storage;
3561 if (local_storage != NULL && rb_id_table_lookup(local_storage,
id, &val)) {
3573 return threadptr_local_aref(rb_thread_ptr(thread),
id);
3640 if (!
id)
return Qnil;
3658rb_thread_fetch(
int argc,
VALUE *argv,
VALUE self)
3669 if (block_given && argc == 2) {
3670 rb_warn(
"block supersedes default value argument");
3675 if (
id == recursive_key) {
3676 return target_th->ec->local_storage_recursive_hash;
3678 else if (
id && target_th->ec->local_storage &&
3679 rb_id_table_lookup(target_th->ec->local_storage,
id, &val)) {
3682 else if (block_given) {
3685 else if (argc == 1) {
3686 rb_key_err_raise(rb_sprintf(
"key not found: %+"PRIsVALUE, key), self, key);
3696 if (
id == recursive_key) {
3697 th->ec->local_storage_recursive_hash = val;
3701 struct rb_id_table *local_storage = th->ec->local_storage;
3704 if (!local_storage)
return Qnil;
3705 rb_id_table_delete(local_storage,
id);
3709 if (local_storage == NULL) {
3710 th->ec->local_storage = local_storage = rb_id_table_create(0);
3712 rb_id_table_insert(local_storage,
id, val);
3725 return threadptr_local_aset(rb_thread_ptr(thread),
id, val);
3776rb_thread_variable_get(
VALUE thread,
VALUE key)
3781 if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
3784 locals = rb_thread_local_storage(thread);
3785 return rb_hash_aref(locals, symbol);
3806 locals = rb_thread_local_storage(thread);
3828 struct rb_id_table *local_storage = rb_thread_ptr(self)->ec->local_storage;
3830 if (!
id || local_storage == NULL) {
3833 return RBOOL(rb_id_table_lookup(local_storage,
id, &val));
3836static enum rb_id_table_iterator_result
3837thread_keys_i(
ID key,
VALUE value,
void *ary)
3840 return ID_TABLE_CONTINUE;
3847 return rb_ractor_living_thread_num(GET_RACTOR()) == 1;
3865rb_thread_keys(
VALUE self)
3867 struct rb_id_table *local_storage = rb_thread_ptr(self)->ec->local_storage;
3868 VALUE ary = rb_ary_new();
3870 if (local_storage) {
3871 rb_id_table_foreach(local_storage, thread_keys_i, (
void *)ary);
3879 rb_ary_push(ary, key);
3901rb_thread_variables(
VALUE thread)
3907 if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
3910 locals = rb_thread_local_storage(thread);
3938 if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
3941 locals = rb_thread_local_storage(thread);
3943 return RBOOL(rb_hash_lookup(locals, symbol) !=
Qnil);
3962rb_thread_priority(
VALUE thread)
3964 return INT2NUM(rb_thread_ptr(thread)->priority);
3995rb_thread_priority_set(
VALUE thread,
VALUE prio)
4000#if USE_NATIVE_THREAD_PRIORITY
4001 target_th->priority =
NUM2INT(prio);
4002 native_thread_apply_priority(th);
4005 if (priority > RUBY_THREAD_PRIORITY_MAX) {
4006 priority = RUBY_THREAD_PRIORITY_MAX;
4008 else if (priority < RUBY_THREAD_PRIORITY_MIN) {
4009 priority = RUBY_THREAD_PRIORITY_MIN;
4011 target_th->priority = (int8_t)priority;
4013 return INT2NUM(target_th->priority);
4018#if defined(NFDBITS) && defined(HAVE_RB_FD_INIT)
4054 FD_ZERO(fds->
fdset);
4060 size_t size = howmany(
rb_fd_max(src), NFDBITS) *
sizeof(fd_mask);
4062 if (size <
sizeof(fd_set))
4063 size =
sizeof(fd_set);
4087 size_t m = howmany(n + 1, NFDBITS) *
sizeof(fd_mask);
4088 size_t o = howmany(fds->
maxfd, NFDBITS) *
sizeof(fd_mask);
4090 if (m <
sizeof(fd_set)) m =
sizeof(fd_set);
4091 if (o <
sizeof(fd_set)) o =
sizeof(fd_set);
4095 memset((
char *)fds->
fdset + o, 0, m - o);
4104 FD_SET(n, fds->
fdset);
4110 if (n >= fds->
maxfd)
return;
4111 FD_CLR(n, fds->
fdset);
4117 if (n >= fds->
maxfd)
return 0;
4118 return FD_ISSET(n, fds->
fdset) != 0;
4124 size_t size = howmany(max, NFDBITS) *
sizeof(fd_mask);
4126 if (size <
sizeof(fd_set)) size =
sizeof(fd_set);
4129 memcpy(dst->
fdset, src, size);
4135 size_t size = howmany(
rb_fd_max(src), NFDBITS) *
sizeof(fd_mask);
4137 if (size <
sizeof(fd_set))
4138 size =
sizeof(fd_set);
4147 fd_set *r = NULL, *w = NULL, *e = NULL;
4160 return select(n, r, w, e, timeout);
4163#define rb_fd_no_init(fds) ((void)((fds)->fdset = 0), (void)((fds)->maxfd = 0))
4170#define FD_ZERO(f) rb_fd_zero(f)
4171#define FD_SET(i, f) rb_fd_set((i), (f))
4172#define FD_CLR(i, f) rb_fd_clr((i), (f))
4173#define FD_ISSET(i, f) rb_fd_isset((i), (f))
4175#elif defined(_WIN32)
4180 set->
capa = FD_SETSIZE;
4182 FD_ZERO(set->
fdset);
4204 SOCKET s = rb_w32_get_osfhandle(fd);
4206 for (i = 0; i < set->
fdset->fd_count; i++) {
4207 if (set->
fdset->fd_array[i] == s) {
4211 if (set->
fdset->fd_count >= (
unsigned)set->
capa) {
4212 set->
capa = (set->
fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
4214 rb_xrealloc_mul_add(
4215 set->
fdset, set->
capa,
sizeof(SOCKET),
sizeof(
unsigned int));
4217 set->
fdset->fd_array[set->
fdset->fd_count++] = s;
4225#define FD_ZERO(f) rb_fd_zero(f)
4226#define FD_SET(i, f) rb_fd_set((i), (f))
4227#define FD_CLR(i, f) rb_fd_clr((i), (f))
4228#define FD_ISSET(i, f) rb_fd_isset((i), (f))
4230#define rb_fd_no_init(fds) (void)((fds)->fdset = 0)
4234#ifndef rb_fd_no_init
4235#define rb_fd_no_init(fds) (void)(fds)
4239wait_retryable(
volatile int *result,
int errnum, rb_hrtime_t *rel, rb_hrtime_t end)
4249 if (rel && hrtime_update_expire(rel, end)) {
4259 return !hrtime_update_expire(rel, end);
4279select_set_free(
VALUE p)
4294 volatile int result = 0;
4296 rb_hrtime_t *to, rel, end = 0;
4298 timeout_prepare(&to, &rel, &end, set->timeout);
4299 volatile rb_hrtime_t endtime = end;
4300#define restore_fdset(dst, src) \
4301 ((dst) ? rb_fd_dup(dst, src) : (void)0)
4302#define do_select_update() \
4303 (restore_fdset(set->rset, &set->orig_rset), \
4304 restore_fdset(set->wset, &set->orig_wset), \
4305 restore_fdset(set->eset, &set->orig_eset), \
4311 BLOCKING_REGION(set->th, {
4314 if (!RUBY_VM_INTERRUPTED(set->th->ec)) {
4315 result = native_fd_select(set->max,
4316 set->rset, set->wset, set->eset,
4317 rb_hrtime2timeval(&tv, to), set->th);
4318 if (result < 0) lerrno = errno;
4320 }, ubf_select, set->th, TRUE);
4322 RUBY_VM_CHECK_INTS_BLOCKING(set->th->ec);
4323 }
while (wait_retryable(&result, lerrno, to, endtime) && do_select_update());
4329 return (
VALUE)result;
4338 set.th = GET_THREAD();
4339 RUBY_VM_CHECK_INTS_BLOCKING(set.th->ec);
4344 set.timeout = timeout;
4346 if (!set.rset && !set.wset && !set.eset) {
4355#define fd_init_copy(f) do { \
4357 rb_fd_resize(set.max - 1, set.f); \
4358 if (&set.orig_##f != set.f) { \
4359 rb_fd_init_copy(&set.orig_##f, set.f); \
4363 rb_fd_no_init(&set.orig_##f); \
4377#define POLLIN_SET (POLLRDNORM | POLLRDBAND | POLLIN | POLLHUP | POLLERR)
4378#define POLLOUT_SET (POLLWRBAND | POLLWRNORM | POLLOUT | POLLERR)
4379#define POLLEX_SET (POLLPRI)
4382# define POLLERR_SET (0)
4386wait_for_single_fd_blocking_region(
rb_thread_t *th,
struct pollfd *fds, nfds_t nfds,
4387 rb_hrtime_t *
const to,
volatile int *lerrno)
4390 volatile int result = 0;
4393 BLOCKING_REGION(th, {
4394 if (!RUBY_VM_INTERRUPTED(th->ec)) {
4395 result = ppoll(fds, nfds, rb_hrtime2timespec(&ts, to), 0);
4396 if (result < 0) *lerrno = errno;
4398 }, ubf_select, th, TRUE);
4406thread_io_wait(
struct rb_io *io,
int fd,
int events,
struct timeval *timeout)
4408 struct pollfd fds[1] = {{
4410 .events = (short)events,
4413 volatile int result = 0;
4416 enum ruby_tag_type state;
4417 volatile int lerrno;
4422 thread_io_setup_wfd(th, fd, &wfd);
4424 if (timeout == NULL && thread_io_wait_events(th, fd, events, NULL)) {
4427 fds[0].revents = events;
4431 EC_PUSH_TAG(wfd.th->ec);
4432 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
4433 rb_hrtime_t *to, rel, end = 0;
4434 RUBY_VM_CHECK_INTS_BLOCKING(wfd.th->ec);
4435 timeout_prepare(&to, &rel, &end, timeout);
4437 nfds = numberof(fds);
4438 result = wait_for_single_fd_blocking_region(wfd.th, fds, nfds, to, &lerrno);
4440 RUBY_VM_CHECK_INTS_BLOCKING(wfd.th->ec);
4441 }
while (wait_retryable(&result, lerrno, to, end));
4446 thread_io_wake_pending_closer(&wfd);
4449 EC_JUMP_TAG(wfd.th->ec, state);
4457 if (fds[0].revents & POLLNVAL) {
4467 if (fds[0].revents & POLLIN_SET)
4468 result |= RB_WAITFD_IN;
4469 if (fds[0].revents & POLLOUT_SET)
4470 result |= RB_WAITFD_OUT;
4471 if (fds[0].revents & POLLEX_SET)
4472 result |= RB_WAITFD_PRI;
4475 if (fds[0].revents & POLLERR_SET)
4494select_single(
VALUE ptr)
4500 args->read, args->write, args->except, args->tv);
4502 args->as.error =
errno;
4505 if (args->read &&
rb_fd_isset(args->as.fd, args->read))
4507 if (args->write &&
rb_fd_isset(args->as.fd, args->write))
4509 if (args->except &&
rb_fd_isset(args->as.fd, args->except))
4516select_single_cleanup(
VALUE ptr)
4520 thread_io_wake_pending_closer(&args->wfd);
4541thread_io_wait(
struct rb_io *io,
int fd,
int events,
struct timeval *timeout)
4550 args.read = (events & RB_WAITFD_IN) ? init_set_fd(fd, &rfds) : NULL;
4551 args.write = (events & RB_WAITFD_OUT) ? init_set_fd(fd, &wfds) : NULL;
4552 args.except = (events & RB_WAITFD_PRI) ? init_set_fd(fd, &efds) : NULL;
4554 thread_io_setup_wfd(th, fd, &args.wfd);
4556 r = (int)
rb_ensure(select_single, ptr, select_single_cleanup, ptr);
4558 errno = args.as.error;
4565rb_thread_wait_for_single_fd(
int fd,
int events,
struct timeval *timeout)
4567 return thread_io_wait(NULL, fd, events, timeout);
4571rb_thread_io_wait(
struct rb_io *io,
int events,
struct timeval * timeout)
4573 return thread_io_wait(io, io->
fd, events, timeout);
4580#ifdef USE_CONSERVATIVE_STACK_END
4582rb_gc_set_stack_end(
VALUE **stack_end_p)
4585COMPILER_WARNING_PUSH
4586#if __has_warning("-Wdangling-pointer")
4587COMPILER_WARNING_IGNORED(-Wdangling-pointer);
4589 *stack_end_p = &stack_end;
4602 if (rb_signal_buff_size() > 0) {
4604 threadptr_trap_interrupt(mth);
4609async_bug_fd(
const char *mesg,
int errno_arg,
int fd)
4612 size_t n = strlcpy(buff, mesg,
sizeof(buff));
4613 if (n <
sizeof(buff)-3) {
4616 rb_async_bug_errno(buff, errno_arg);
4621consume_communication_pipe(
int fd)
4627 static char buff[1024];
4633 result = read(fd, buff,
sizeof(buff));
4635 RUBY_DEBUG_LOG(
"resultf:%d buff:%lu", (
int)result, (
unsigned long)buff[0]);
4637 RUBY_DEBUG_LOG(
"result:%d", (
int)result);
4641 if (USE_EVENTFD || result < (ssize_t)
sizeof(buff)) {
4645 else if (result == 0) {
4648 else if (result < 0) {
4654#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
4659 async_bug_fd(
"consume_communication_pipe: read", e, fd);
4666rb_thread_stop_timer_thread(
void)
4668 if (TIMER_THREAD_CREATED_P() && native_stop_timer_thread()) {
4669 native_reset_timer_thread();
4674rb_thread_reset_timer_thread(
void)
4676 native_reset_timer_thread();
4680rb_thread_start_timer_thread(
void)
4683 rb_thread_create_timer_thread();
4687clear_coverage_i(st_data_t key, st_data_t val, st_data_t dummy)
4695 if (GET_VM()->coverage_mode & COVERAGE_TARGET_ONESHOT_LINES) {
4696 rb_ary_clear(lines);
4717rb_clear_coverages(
void)
4719 VALUE coverages = rb_get_coverages();
4720 if (
RTEST(coverages)) {
4725#if defined(HAVE_WORKING_FORK)
4733 vm->ractor.main_ractor = r;
4734 vm->ractor.main_thread = th;
4735 r->threads.main = th;
4736 r->status_ = ractor_created;
4738 thread_sched_atfork(TH_SCHED(th));
4742 ccan_list_for_each(&vm->ractor.set, r, vmlr_node) {
4743 ccan_list_for_each(&r->threads.set, i, lt_node) {
4747 rb_vm_living_threads_init(vm);
4749 rb_ractor_atfork(vm, th);
4750 rb_vm_postponed_job_atfork();
4754 ccan_list_head_init(&th->interrupt_exec_tasks);
4757 rb_ractor_sleeper_threads_clear(th->ractor);
4758 rb_clear_coverages();
4761 rb_thread_reset_timer_thread();
4762 rb_thread_start_timer_thread();
4764 VM_ASSERT(vm->ractor.blocking_cnt == 0);
4765 VM_ASSERT(vm->ractor.cnt == 1);
4771 if (th != current_th) {
4773 rb_mutex_abandon_keeping_mutexes(th);
4774 rb_mutex_abandon_locking_mutex(th);
4775 thread_cleanup_func(th, TRUE);
4784 rb_threadptr_pending_interrupt_clear(th);
4785 rb_thread_atfork_internal(th, terminate_atfork_i);
4786 th->join_list = NULL;
4787 rb_fiber_atfork(th);
4796 if (th != current_th) {
4797 thread_cleanup_func_before_exec(th);
4805 rb_thread_atfork_internal(th, terminate_atfork_before_exec_i);
4830 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE
4853thgroup_s_alloc(
VALUE klass)
4874thgroup_list(
VALUE group)
4876 VALUE ary = rb_ary_new();
4880 ccan_list_for_each(&r->threads.set, th, lt_node) {
4881 if (th->thgroup == group) {
4882 rb_ary_push(ary, th->self);
4906thgroup_enclose(
VALUE group)
4925thgroup_enclosed_p(
VALUE group)
4930 return RBOOL(data->enclosed);
4970 if (data->enclosed) {
4978 if (data->enclosed) {
4980 "can't move from the enclosed thread group");
4983 target_th->thgroup = group;
4991thread_shield_mark(
void *ptr)
4993 rb_gc_mark((
VALUE)ptr);
4998 {thread_shield_mark, 0, 0,},
4999 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
5003thread_shield_alloc(
VALUE klass)
5008#define GetThreadShieldPtr(obj) ((VALUE)rb_check_typeddata((obj), &thread_shield_data_type))
5009#define THREAD_SHIELD_WAITING_MASK (((FL_USER19-1)&~(FL_USER0-1))|FL_USER19)
5010#define THREAD_SHIELD_WAITING_SHIFT (FL_USHIFT)
5011#define THREAD_SHIELD_WAITING_MAX (THREAD_SHIELD_WAITING_MASK>>THREAD_SHIELD_WAITING_SHIFT)
5012STATIC_ASSERT(THREAD_SHIELD_WAITING_MAX, THREAD_SHIELD_WAITING_MAX <= UINT_MAX);
5013static inline unsigned int
5014rb_thread_shield_waiting(
VALUE b)
5016 return ((
RBASIC(b)->flags&THREAD_SHIELD_WAITING_MASK)>>THREAD_SHIELD_WAITING_SHIFT);
5020rb_thread_shield_waiting_inc(
VALUE b)
5022 unsigned int w = rb_thread_shield_waiting(b);
5024 if (w > THREAD_SHIELD_WAITING_MAX)
5026 RBASIC(b)->flags &= ~THREAD_SHIELD_WAITING_MASK;
5027 RBASIC(b)->flags |= ((
VALUE)w << THREAD_SHIELD_WAITING_SHIFT);
5031rb_thread_shield_waiting_dec(
VALUE b)
5033 unsigned int w = rb_thread_shield_waiting(b);
5036 RBASIC(b)->flags &= ~THREAD_SHIELD_WAITING_MASK;
5037 RBASIC(b)->flags |= ((
VALUE)w << THREAD_SHIELD_WAITING_SHIFT);
5041rb_thread_shield_new(
void)
5043 VALUE thread_shield = thread_shield_alloc(rb_cThreadShield);
5045 return thread_shield;
5049rb_thread_shield_owned(
VALUE self)
5051 VALUE mutex = GetThreadShieldPtr(self);
5052 if (!mutex)
return false;
5056 return m->fiber == GET_EC()->fiber_ptr;
5068rb_thread_shield_wait(
VALUE self)
5070 VALUE mutex = GetThreadShieldPtr(self);
5073 if (!mutex)
return Qfalse;
5074 m = mutex_ptr(mutex);
5075 if (m->fiber == GET_EC()->fiber_ptr)
return Qnil;
5076 rb_thread_shield_waiting_inc(self);
5078 rb_thread_shield_waiting_dec(self);
5081 return rb_thread_shield_waiting(self) > 0 ?
Qnil :
Qfalse;
5085thread_shield_get_mutex(
VALUE self)
5087 VALUE mutex = GetThreadShieldPtr(self);
5089 rb_raise(
rb_eThreadError,
"destroyed thread shield - %p", (
void *)self);
5097rb_thread_shield_release(
VALUE self)
5099 VALUE mutex = thread_shield_get_mutex(self);
5101 return RBOOL(rb_thread_shield_waiting(self) > 0);
5108rb_thread_shield_destroy(
VALUE self)
5110 VALUE mutex = thread_shield_get_mutex(self);
5113 return RBOOL(rb_thread_shield_waiting(self) > 0);
5119 return th->ec->local_storage_recursive_hash;
5125 th->ec->local_storage_recursive_hash = hash;
5137recursive_list_access(
VALUE sym)
5140 VALUE hash = threadptr_recursive_hash(th);
5143 hash = rb_ident_hash_new();
5144 threadptr_recursive_hash_set(th, hash);
5148 list = rb_hash_aref(hash, sym);
5151 list = rb_ident_hash_new();
5152 rb_hash_aset(hash, sym, list);
5166#if SIZEOF_LONG == SIZEOF_VOIDP
5167 #define OBJ_ID_EQL(obj_id, other) ((obj_id) == (other))
5168#elif SIZEOF_LONG_LONG == SIZEOF_VOIDP
5169 #define OBJ_ID_EQL(obj_id, other) (RB_BIGNUM_TYPE_P((obj_id)) ? \
5170 rb_big_eql((obj_id), (other)) : ((obj_id) == (other)))
5173 VALUE pair_list = rb_hash_lookup2(list, obj,
Qundef);
5174 if (UNDEF_P(pair_list))
5176 if (paired_obj_id) {
5178 if (!OBJ_ID_EQL(paired_obj_id, pair_list))
5182 if (
NIL_P(rb_hash_lookup(pair_list, paired_obj_id)))
5204 rb_hash_aset(list, obj,
Qtrue);
5206 else if (UNDEF_P(pair_list = rb_hash_lookup2(list, obj,
Qundef))) {
5207 rb_hash_aset(list, obj, paired_obj);
5211 VALUE other_paired_obj = pair_list;
5212 pair_list = rb_hash_new();
5213 rb_hash_aset(pair_list, other_paired_obj,
Qtrue);
5214 rb_hash_aset(list, obj, pair_list);
5216 rb_hash_aset(pair_list, paired_obj,
Qtrue);
5232 VALUE pair_list = rb_hash_lookup2(list, obj,
Qundef);
5233 if (UNDEF_P(pair_list)) {
5237 rb_hash_delete_entry(pair_list, paired_obj);
5243 rb_hash_delete_entry(list, obj);
5259 return (*p->func)(p->obj, p->arg, FALSE);
5280 p.list = recursive_list_access(sym);
5284 outermost = outer && !recursive_check(p.list,
ID2SYM(recursive_key), 0);
5286 if (recursive_check(p.list, p.obj, pairid)) {
5287 if (outer && !outermost) {
5290 return (*func)(obj, arg, TRUE);
5293 enum ruby_tag_type state;
5298 recursive_push(p.list,
ID2SYM(recursive_key), 0);
5299 recursive_push(p.list, p.obj, p.pairid);
5300 result = rb_catch_protect(p.list, exec_recursive_i, (
VALUE)&p, &state);
5301 if (!recursive_pop(p.list, p.obj, p.pairid))
goto invalid;
5302 if (!recursive_pop(p.list,
ID2SYM(recursive_key), 0))
goto invalid;
5303 if (state != TAG_NONE) EC_JUMP_TAG(GET_EC(), state);
5304 if (result == p.list) {
5305 result = (*func)(obj, arg, TRUE);
5310 recursive_push(p.list, p.obj, p.pairid);
5311 EC_PUSH_TAG(GET_EC());
5312 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
5313 ret = (*func)(obj, arg, FALSE);
5316 if (!recursive_pop(p.list, p.obj, p.pairid)) {
5319 if (state != TAG_NONE) EC_JUMP_TAG(GET_EC(), state);
5328 "for %+"PRIsVALUE
" in %+"PRIsVALUE,
5352 return exec_recursive(func, obj, rb_memory_id(paired_obj), arg, 0,
rb_frame_last_func());
5370 return exec_recursive(func, obj, 0, arg, 1, mid);
5382 return exec_recursive(func, obj, rb_memory_id(paired_obj), arg, 1,
rb_frame_last_func());
5394rb_thread_backtrace_m(
int argc,
VALUE *argv,
VALUE thval)
5396 return rb_vm_thread_backtrace(argc, argv, thval);
5411rb_thread_backtrace_locations_m(
int argc,
VALUE *argv,
VALUE thval)
5413 return rb_vm_thread_backtrace_locations(argc, argv, thval);
5417Init_Thread_Mutex(
void)
5506 rb_vm_register_special_exception(ruby_error_stream_closed,
rb_eIOError,
5507 "stream closed in another thread");
5516 const char * ptr = getenv(
"RUBY_THREAD_TIMESLICE");
5519 long quantum = strtol(ptr, NULL, 0);
5520 if (quantum > 0 && !(SIZEOF_LONG > 4 && quantum > UINT32_MAX)) {
5521 thread_default_quantum_ms = (uint32_t)quantum;
5524 fprintf(stderr,
"Ignored RUBY_THREAD_TIMESLICE=%s\n", ptr);
5529 th->thgroup = th->ractor->thgroup_default =
rb_obj_alloc(cThGroup);
5530 rb_define_const(cThGroup,
"Default", th->thgroup);
5540#ifdef HAVE_PTHREAD_NP_H
5541 VM_ASSERT(TH_SCHED(th)->running == th);
5547 th->pending_interrupt_queue = rb_ary_hidden_new(0);
5548 th->pending_interrupt_queue_checked = 0;
5549 th->pending_interrupt_mask_stack = rb_ary_hidden_new(0);
5553 rb_thread_create_timer_thread();
5569#ifdef NON_SCALAR_THREAD_ID
5570 #define thread_id_str(th) (NULL)
5572 #define thread_id_str(th) ((void *)(uintptr_t)(th)->nt->thread_id)
5581 rb_str_catf(msg,
"\n%d threads, %d sleeps current:%p main thread:%p\n",
5582 rb_ractor_living_thread_num(r), rb_ractor_sleeper_thread_num(r),
5583 (
void *)GET_THREAD(), (
void *)r->threads.main);
5585 ccan_list_for_each(&r->threads.set, th, lt_node) {
5586 rb_str_catf(msg,
"* %+"PRIsVALUE
"\n rb_thread_t:%p "
5588 th->self, (
void *)th, th->nt ? thread_id_str(th) :
"N/A", th->ec->interrupt_flag);
5590 if (th->locking_mutex) {
5591 rb_mutex_t *mutex = mutex_ptr(th->locking_mutex);
5592 rb_str_catf(msg,
" mutex:%p cond:%"PRIuSIZE,
5593 (
void *)mutex->fiber, rb_mutex_num_waiting(mutex));
5599 rb_str_catf(msg,
"\n depended by: tb_thread_id:%p", (
void *)list->thread);
5603 rb_str_catf(msg,
"\n ");
5604 rb_str_concat(msg, rb_ary_join(rb_ec_backtrace_str_ary(th->ec, RUBY_BACKTRACE_START, RUBY_ALL_BACKTRACE_LINES), sep));
5605 rb_str_catf(msg,
"\n");
5612 if (GET_THREAD()->vm->thread_ignore_deadlock)
return;
5614#ifdef RUBY_THREAD_PTHREAD_H
5615 if (r->threads.sched.readyq_cnt > 0)
return;
5618 int sleeper_num = rb_ractor_sleeper_thread_num(r);
5619 int ltnum = rb_ractor_living_thread_num(r);
5621 if (ltnum > sleeper_num)
return;
5622 if (ltnum < sleeper_num) rb_bug(
"sleeper must not be more than vm_living_thread_num(vm)");
5627 ccan_list_for_each(&r->threads.set, th, lt_node) {
5628 if (th->status != THREAD_STOPPED_FOREVER || RUBY_VM_INTERRUPTED(th->ec)) {
5631 else if (th->locking_mutex) {
5632 rb_mutex_t *mutex = mutex_ptr(th->locking_mutex);
5633 if (mutex->fiber == th->ec->fiber_ptr || (!mutex->fiber && !ccan_list_empty(&mutex->waitq))) {
5644 argv[1] =
rb_str_new2(
"No live threads left. Deadlock?");
5645 debug_deadlock_check(r, argv[1]);
5646 rb_ractor_sleeper_threads_dec(GET_RACTOR());
5647 rb_threadptr_raise(r->threads.main, 2, argv);
5654rb_vm_memsize_waiting_fds(
struct ccan_list_head *waiting_fds)
5659 ccan_list_for_each(waiting_fds, waitfd, wfd_node) {
5670 VALUE coverage = rb_iseq_coverage(cfp->iseq);
5675 VM_ASSERT(line >= 0);
5679 if (GET_VM()->coverage_mode & COVERAGE_TARGET_ONESHOT_LINES) {
5680 rb_iseq_clear_event_flags(cfp->iseq, cfp->pc - ISEQ_BODY(cfp->iseq)->iseq_encoded - 1, RUBY_EVENT_COVERAGE_LINE);
5681 rb_ary_push(lines,
LONG2FIX(line + 1));
5701 VALUE coverage = rb_iseq_coverage(cfp->iseq);
5705 long pc = cfp->pc - ISEQ_BODY(cfp->iseq)->iseq_encoded - 1;
5720 VALUE path, beg_pos_lineno, beg_pos_column, end_pos_lineno, end_pos_column;
5722 if (!me->def)
return NULL;
5725 switch (me->def->type) {
5726 case VM_METHOD_TYPE_ISEQ: {
5729 path = rb_iseq_path(iseq);
5730 beg_pos_lineno =
INT2FIX(loc->code_location.beg_pos.lineno);
5731 beg_pos_column =
INT2FIX(loc->code_location.beg_pos.column);
5732 end_pos_lineno =
INT2FIX(loc->code_location.end_pos.lineno);
5733 end_pos_column =
INT2FIX(loc->code_location.end_pos.column);
5736 case VM_METHOD_TYPE_BMETHOD: {
5737 const rb_iseq_t *iseq = rb_proc_get_iseq(me->def->body.bmethod.proc, 0);
5740 rb_iseq_check(iseq);
5741 path = rb_iseq_path(iseq);
5742 loc = &ISEQ_BODY(iseq)->location;
5743 beg_pos_lineno =
INT2FIX(loc->code_location.beg_pos.lineno);
5744 beg_pos_column =
INT2FIX(loc->code_location.beg_pos.column);
5745 end_pos_lineno =
INT2FIX(loc->code_location.end_pos.lineno);
5746 end_pos_column =
INT2FIX(loc->code_location.end_pos.column);
5751 case VM_METHOD_TYPE_ALIAS:
5752 me = me->def->body.alias.original_me;
5754 case VM_METHOD_TYPE_REFINED:
5755 me = me->def->body.refined.orig_me;
5756 if (!me)
return NULL;
5764 path = rb_ary_entry(path, 1);
5767 if (resolved_location) {
5768 resolved_location[0] = path;
5769 resolved_location[1] = beg_pos_lineno;
5770 resolved_location[2] = beg_pos_column;
5771 resolved_location[3] = end_pos_lineno;
5772 resolved_location[4] = end_pos_column;
5786 me = rb_resolve_me_location(me, 0);
5789 rcount = rb_hash_aref(me2counter, (
VALUE) me);
5797rb_get_coverages(
void)
5799 return GET_VM()->coverages;
5803rb_get_coverage_mode(
void)
5805 return GET_VM()->coverage_mode;
5809rb_set_coverages(
VALUE coverages,
int mode,
VALUE me2counter)
5811 GET_VM()->coverages = coverages;
5812 GET_VM()->me2counter = me2counter;
5813 GET_VM()->coverage_mode = mode;
5817rb_resume_coverages(
void)
5819 int mode = GET_VM()->coverage_mode;
5820 VALUE me2counter = GET_VM()->me2counter;
5821 rb_add_event_hook2((
rb_event_hook_func_t) update_line_coverage, RUBY_EVENT_COVERAGE_LINE,
Qnil, RUBY_EVENT_HOOK_FLAG_SAFE | RUBY_EVENT_HOOK_FLAG_RAW_ARG);
5822 if (mode & COVERAGE_TARGET_BRANCHES) {
5823 rb_add_event_hook2((
rb_event_hook_func_t) update_branch_coverage, RUBY_EVENT_COVERAGE_BRANCH,
Qnil, RUBY_EVENT_HOOK_FLAG_SAFE | RUBY_EVENT_HOOK_FLAG_RAW_ARG);
5825 if (mode & COVERAGE_TARGET_METHODS) {
5831rb_suspend_coverages(
void)
5834 if (GET_VM()->coverage_mode & COVERAGE_TARGET_BRANCHES) {
5837 if (GET_VM()->coverage_mode & COVERAGE_TARGET_METHODS) {
5844rb_reset_coverages(
void)
5846 rb_clear_coverages();
5847 rb_iseq_remove_coverage_all();
5848 GET_VM()->coverages =
Qfalse;
5852rb_default_coverage(
int n)
5854 VALUE coverage = rb_ary_hidden_new_fill(3);
5856 int mode = GET_VM()->coverage_mode;
5858 if (mode & COVERAGE_TARGET_LINES) {
5859 lines = n > 0 ? rb_ary_hidden_new_fill(n) : rb_ary_hidden_new(0);
5861 RARRAY_ASET(coverage, COVERAGE_INDEX_LINES, lines);
5863 if (mode & COVERAGE_TARGET_BRANCHES) {
5864 branches = rb_ary_hidden_new_fill(2);
5886 VALUE structure = rb_hash_new();
5892 RARRAY_ASET(coverage, COVERAGE_INDEX_BRANCHES, branches);
5898uninterruptible_exit(
VALUE v)
5901 rb_ary_pop(cur_th->pending_interrupt_mask_stack);
5903 cur_th->pending_interrupt_queue_checked = 0;
5904 if (!rb_threadptr_pending_interrupt_empty_p(cur_th)) {
5905 RUBY_VM_SET_INTERRUPT(cur_th->ec);
5913 VALUE interrupt_mask = rb_ident_hash_new();
5916 rb_hash_aset(interrupt_mask, rb_cObject, sym_never);
5918 rb_ary_push(cur_th->pending_interrupt_mask_stack, interrupt_mask);
5922 RUBY_VM_CHECK_INTS(cur_th->ec);
5929 VM_ASSERT(th->specific_storage == NULL);
5931 if (UNLIKELY(specific_key_count > 0)) {
5932 th->specific_storage =
ZALLOC_N(
void *, RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX);
5936rb_internal_thread_specific_key_t
5941 if (specific_key_count == 0 && vm->ractor.cnt > 1) {
5942 rb_raise(
rb_eThreadError,
"The first rb_internal_thread_specific_key_create() is called with multiple ractors");
5944 else if (specific_key_count > RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX) {
5945 rb_raise(
rb_eThreadError,
"rb_internal_thread_specific_key_create() is called more than %d times", RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX);
5948 rb_internal_thread_specific_key_t key = specific_key_count++;
5955 ccan_list_for_each(&cr->threads.set, th, lt_node) {
5956 thread_specific_storage_alloc(th);
5969 VM_ASSERT(rb_thread_ptr(thread_val) == th);
5970 VM_ASSERT(key < RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX);
5971 VM_ASSERT(th->specific_storage);
5973 return th->specific_storage[key];
5982 VM_ASSERT(rb_thread_ptr(thread_val) == th);
5983 VM_ASSERT(key < RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX);
5984 VM_ASSERT(th->specific_storage);
5986 th->specific_storage[key] = data;
5992 struct ccan_list_node node;
5994 rb_interrupt_exec_func_t *func;
5996 enum rb_interrupt_exec_flag flags;
6000rb_threadptr_interrupt_exec_task_mark(
rb_thread_t *th)
6004 ccan_list_for_each(&th->interrupt_exec_tasks, task, node) {
6005 if (task->flags & rb_interrupt_exec_flag_value_data) {
6006 rb_gc_mark((
VALUE)task->data);
6014rb_threadptr_interrupt_exec(
rb_thread_t *th, rb_interrupt_exec_func_t *func,
void *data,
enum rb_interrupt_exec_flag flags)
6026 ccan_list_add_tail(&th->interrupt_exec_tasks, &task->node);
6027 threadptr_interrupt_locked(th,
true);
6045 (*task->func)(task->data);
6069 rb_interrupt_exec_func_t *func;
6074interrupt_ractor_new_thread_func(
void *data)
6084interrupt_ractor_func(
void *data)
6094 rb_interrupt_exec_func_t *func,
void *data,
enum rb_interrupt_exec_flag flags)
6101 rb_threadptr_interrupt_exec(main_th, interrupt_ractor_func, d, flags);
#define RUBY_ASSERT_ALWAYS(expr,...)
A variant of RUBY_ASSERT that does not interface with RUBY_DEBUG.
std::atomic< unsigned > rb_atomic_t
Type that is eligible for atomic operations.
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
#define RUBY_INTERNAL_EVENT_SWITCH
Thread switched.
int rb_remove_event_hook(rb_event_hook_func_t func)
Removes the passed function from the list of event hooks.
#define RUBY_EVENT_THREAD_BEGIN
Encountered a new thread.
void(* rb_event_hook_func_t)(rb_event_flag_t evflag, VALUE data, VALUE self, ID mid, VALUE klass)
Type of event hooks.
uint32_t rb_event_flag_t
Represents event(s).
#define RUBY_EVENT_CALL
A method, written in Ruby, is called.
#define RUBY_EVENT_THREAD_END
Encountered an end of a thread.
static void RB_FL_SET_RAW(VALUE obj, VALUE flags)
This is an implementation detail of RB_FL_SET().
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
ID rb_frame_last_func(void)
Returns the ID of the last method in the call stack.
int rb_keyword_given_p(void)
Determines if the current method is given a keyword argument.
int rb_block_given_p(void)
Determines if the current method is given a block.
#define rb_str_new2
Old name of rb_str_new_cstr.
#define ALLOC
Old name of RB_ALLOC.
#define T_STRING
Old name of RUBY_T_STRING.
#define xfree
Old name of ruby_xfree.
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
#define OBJ_FROZEN
Old name of RB_OBJ_FROZEN.
#define xrealloc
Old name of ruby_xrealloc.
#define ID2SYM
Old name of RB_ID2SYM.
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
#define CLASS_OF
Old name of rb_class_of.
#define xmalloc
Old name of ruby_xmalloc.
#define LONG2FIX
Old name of RB_INT2FIX.
#define FIX2INT
Old name of RB_FIX2INT.
#define ZALLOC_N
Old name of RB_ZALLOC_N.
#define T_ICLASS
Old name of RUBY_T_ICLASS.
#define T_HASH
Old name of RUBY_T_HASH.
#define Qtrue
Old name of RUBY_Qtrue.
#define NUM2INT
Old name of RB_NUM2INT.
#define INT2NUM
Old name of RB_INT2NUM.
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define FIX2LONG
Old name of RB_FIX2LONG.
#define T_ARRAY
Old name of RUBY_T_ARRAY.
#define T_OBJECT
Old name of RUBY_T_OBJECT.
#define NIL_P
Old name of RB_NIL_P.
#define POSFIXABLE
Old name of RB_POSFIXABLE.
#define BUILTIN_TYPE
Old name of RB_BUILTIN_TYPE.
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define SYMBOL_P
Old name of RB_SYMBOL_P.
void ruby_stop(int ex)
Calls ruby_cleanup() and exits the process.
#define ruby_debug
This variable controls whether the interpreter is in debug mode.
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
VALUE rb_eSystemExit
SystemExit exception.
VALUE rb_eIOError
IOError exception.
VALUE rb_eStandardError
StandardError exception.
VALUE rb_eTypeError
TypeError exception.
void rb_frozen_error_raise(VALUE frozen_obj, const char *fmt,...)
Raises an instance of rb_eFrozenError.
VALUE rb_eFatal
fatal exception.
VALUE rb_eRuntimeError
RuntimeError exception.
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
VALUE rb_exc_new(VALUE etype, const char *ptr, long len)
Creates an instance of the passed exception class.
VALUE rb_eException
Mother of all exceptions.
VALUE rb_eThreadError
ThreadError exception.
void rb_exit(int status)
Terminates the current execution context.
VALUE rb_eSignal
SignalException exception.
VALUE rb_obj_alloc(VALUE klass)
Allocates an instance of the given class.
VALUE rb_cInteger
Module class.
VALUE rb_obj_hide(VALUE obj)
Make the object invisible from Ruby code.
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
VALUE rb_cThread
Thread class.
VALUE rb_cModule
Module class.
double rb_num2dbl(VALUE num)
Converts an instance of rb_cNumeric into C's double.
VALUE rb_obj_is_kind_of(VALUE obj, VALUE klass)
Queries if the given object is an instance (of possibly descendants) of the given class.
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
VALUE rb_block_proc(void)
Constructs a Proc object from implicitly passed components.
void rb_reset_random_seed(void)
Resets the RNG behind rb_genrand_int32()/rb_genrand_real().
VALUE rb_str_new_frozen(VALUE str)
Creates a frozen copy of the string, if necessary.
VALUE rb_str_concat(VALUE dst, VALUE src)
Identical to rb_str_append(), except it also accepts an integer as a codepoint.
#define rb_str_cat_cstr(buf, str)
Identical to rb_str_cat(), except it assumes the passed pointer is a pointer to a C string.
#define rb_str_new_cstr(str)
Identical to rb_str_new, except it assumes the passed pointer is a pointer to a C string.
int rb_thread_interrupted(VALUE thval)
Checks if the thread's execution was recently interrupted.
VALUE rb_thread_local_aref(VALUE thread, ID key)
This badly named function reads from a Fiber local storage.
VALUE rb_mutex_new(void)
Creates a mutex.
VALUE rb_thread_kill(VALUE thread)
Terminates the given thread.
#define RUBY_UBF_IO
A special UBF for blocking IO operations.
VALUE rb_thread_main(void)
Obtains the "main" thread.
VALUE rb_exec_recursive(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE h)
"Recursion" API entry point.
void rb_thread_sleep_forever(void)
Blocks indefinitely.
void rb_thread_fd_close(int fd)
Notifies a closing of a file descriptor to other threads.
void rb_thread_wait_for(struct timeval time)
Identical to rb_thread_sleep(), except it takes struct timeval instead.
VALUE rb_thread_stop(void)
Stops the current thread.
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_exec_recursive_paired(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE p, VALUE h)
Identical to rb_exec_recursive(), except it checks for the recursion on the ordered pair of { g,...
void rb_unblock_function_t(void *)
This is the type of UBFs.
void rb_thread_atfork_before_exec(void)
:FIXME: situation of this function is unclear.
void rb_thread_check_ints(void)
Checks for interrupts.
VALUE rb_thread_run(VALUE thread)
This is a rb_thread_wakeup() + rb_thread_schedule() combo.
VALUE rb_thread_wakeup(VALUE thread)
Marks a given thread as eligible for scheduling.
VALUE rb_mutex_unlock(VALUE mutex)
Releases the mutex.
VALUE rb_exec_recursive_paired_outer(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE p, VALUE h)
Identical to rb_exec_recursive_outer(), except it checks for the recursion on the ordered pair of { g...
void rb_thread_sleep_deadly(void)
Identical to rb_thread_sleep_forever(), except the thread calling this function is considered "dead" ...
void rb_thread_atfork(void)
A pthread_atfork(3posix)-like API.
VALUE rb_thread_current(void)
Obtains the "current" thread.
int rb_thread_alone(void)
Checks if the thread this function is running is the only thread that is currently alive.
VALUE rb_thread_local_aset(VALUE thread, ID key, VALUE val)
This badly named function writes to a Fiber local storage.
void rb_thread_schedule(void)
Tries to switch to another thread.
#define RUBY_UBF_PROCESS
A special UBF for blocking process operations.
VALUE rb_exec_recursive_outer(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE h)
Identical to rb_exec_recursive(), except it calls f for outermost recursion only.
VALUE rb_thread_wakeup_alive(VALUE thread)
Identical to rb_thread_wakeup(), except it doesn't raise on an already killed thread.
VALUE rb_mutex_lock(VALUE mutex)
Attempts to lock the mutex.
void rb_thread_sleep(int sec)
Blocks for the given period of time.
void rb_timespec_now(struct timespec *ts)
Fills the current time into the given struct.
struct timeval rb_time_timeval(VALUE time)
Converts an instance of rb_cTime to a struct timeval that represents the identical point of time.
VALUE rb_ivar_set(VALUE obj, ID name, VALUE val)
Identical to rb_iv_set(), except it accepts the name as an ID instead of a C string.
VALUE rb_ivar_get(VALUE obj, ID name)
Identical to rb_iv_get(), except it accepts the name as an ID instead of a C string.
VALUE rb_class_path(VALUE mod)
Identical to rb_mod_name(), except it returns #<Class: ...> style inspection for anonymous modules.
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
int rb_sourceline(void)
Resembles __LINE__.
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
ID rb_check_id(volatile VALUE *namep)
Detects if the given name is already interned or not.
VALUE rb_to_symbol(VALUE name)
Identical to rb_intern_str(), except it generates a dynamic symbol if necessary.
VALUE rb_eIOTimeoutError
Indicates that a timeout has occurred while performing an IO operation.
#define RB_NOGVL_UBF_ASYNC_SAFE
Passing this flag to rb_nogvl() indicates that the passed UBF is async-signal-safe.
void * rb_internal_thread_specific_get(VALUE thread_val, rb_internal_thread_specific_key_t key)
Get thread and tool specific data.
#define RB_NOGVL_INTR_FAIL
Passing this flag to rb_nogvl() prevents it from checking interrupts.
void rb_internal_thread_specific_set(VALUE thread_val, rb_internal_thread_specific_key_t key, void *data)
Set thread and tool specific data.
rb_internal_thread_specific_key_t rb_internal_thread_specific_key_create(void)
Create a key to store thread specific data.
void * rb_nogvl(void *(*func)(void *), void *data1, rb_unblock_function_t *ubf, void *data2, int flags)
Identical to rb_thread_call_without_gvl(), except it additionally takes "flags" that change the behav...
void * rb_thread_call_with_gvl(void *(*func)(void *), void *data1)
(Re-)acquires the GVL.
#define RB_NOGVL_OFFLOAD_SAFE
Passing this flag to rb_nogvl() indicates that the passed function is safe to offload to a background...
void * rb_thread_call_without_gvl2(void *(*func)(void *), void *data1, rb_unblock_function_t *ubf, void *data2)
Identical to rb_thread_call_without_gvl(), except it does not interface with signals etc.
void * rb_thread_call_without_gvl(void *(*func)(void *), void *data1, rb_unblock_function_t *ubf, void *data2)
Allows the passed function to run in parallel with other Ruby threads.
#define RB_BLOCK_CALL_FUNC_ARGLIST(yielded_arg, callback_arg)
Shim for block function parameters.
VALUE rb_yield(VALUE val)
Yields the block.
void rb_throw_obj(VALUE tag, VALUE val)
Identical to rb_throw(), except it allows arbitrary Ruby object to become a tag.
static int rb_fd_max(const rb_fdset_t *f)
It seems this function has no use.
void rb_fd_copy(rb_fdset_t *dst, const fd_set *src, int max)
Destructively overwrites an fdset with another.
void rb_fd_dup(rb_fdset_t *dst, const rb_fdset_t *src)
Identical to rb_fd_copy(), except it copies unlimited number of file descriptors.
void rb_fd_term(rb_fdset_t *f)
Destroys the rb_fdset_t, releasing any memory and resources it used.
static fd_set * rb_fd_ptr(const rb_fdset_t *f)
Raw pointer to fd_set.
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
#define ALLOCA_N(type, n)
#define MEMZERO(p, type, n)
Handy macro to erase a region of memory.
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
VALUE rb_thread_create(type *q, void *w)
Creates a rb_cThread instance.
void rb_hash_foreach(VALUE q, int_type *w, VALUE e)
Iteration over the given hash.
VALUE rb_ensure(type *q, VALUE w, type *e, VALUE r)
An equivalent of ensure clause.
#define rb_fd_isset
Queries if the given fd is in the rb_fdset_t.
#define rb_fd_select
Waits for multiple file descriptors at once.
#define rb_fd_init
Initialises the :given :rb_fdset_t.
#define rb_fd_set
Sets the given fd to the rb_fdset_t.
#define rb_fd_zero
Clears the given rb_fdset_t.
#define rb_fd_clr
Unsets the given fd from the rb_fdset_t.
#define RARRAY_LEN
Just another name of rb_array_len.
static int RARRAY_LENINT(VALUE ary)
Identical to rb_array_len(), except it differs for the return type.
static void RARRAY_ASET(VALUE ary, long i, VALUE v)
Assigns an object in an array.
#define RARRAY_AREF(a, i)
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
static VALUE RBASIC_CLASS(VALUE obj)
Queries the class of an object.
#define RBASIC(obj)
Convenient casting macro.
#define RCLASS_SUPER
Just another name of rb_class_get_superclass.
#define DATA_PTR(obj)
Convenient getter macro.
#define RHASH_EMPTY_P(h)
Checks if the hash is empty.
#define StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
#define RUBY_TYPED_DEFAULT_FREE
This is a value you can set to rb_data_type_struct::dfree.
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
#define TypedData_Wrap_Struct(klass, data_type, sval)
Converts sval, a pointer to your struct, into a Ruby object.
#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...
#define errno
Ractor-aware version of errno.
int ruby_native_thread_p(void)
Queries if the thread which calls this function is a ruby's thread.
int ruby_snprintf(char *str, size_t n, char const *fmt,...)
Our own locale-insensitive version of snprintf(3).
#define RB_PASS_CALLED_KEYWORDS
Pass keywords if current method is called with keywords, useful for argument delegation.
VALUE rb_fiber_scheduler_blocking_operation_wait(VALUE scheduler, void *(*function)(void *), void *data, rb_unblock_function_t *unblock_function, void *data2, int flags, struct rb_fiber_scheduler_blocking_operation_state *state)
Defer the execution of the passed function to the scheduler.
VALUE rb_fiber_scheduler_current(void)
Identical to rb_fiber_scheduler_get(), except it also returns RUBY_Qnil in case of a blocking fiber.
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....
VALUE rb_fiber_scheduler_set(VALUE scheduler)
Destructively assigns the passed scheduler to that of the current thread that is calling this functio...
VALUE rb_fiber_scheduler_unblock(VALUE scheduler, VALUE blocker, VALUE fiber)
Wakes up a fiber previously blocked using rb_fiber_scheduler_block().
int rb_thread_fd_select(int nfds, rb_fdset_t *rfds, rb_fdset_t *wfds, rb_fdset_t *efds, struct timeval *timeout)
Waits for multiple file descriptors at once.
#define rb_fd_resize(n, f)
Does nothing (defined for compatibility).
static bool RB_TEST(VALUE obj)
Emulates Ruby's "if" statement.
#define RTEST
This is an old name of RB_TEST.
#define _(args)
This was a transition path from K&R to ANSI.
This is the struct that holds necessary info for a struct.
The data structure which wraps the fd_set bitmap used by select(2).
int maxfd
Maximum allowed number of FDs.
fd_set * fdset
File descriptors buffer.
int capa
Maximum allowed number of FDs.
Ruby's IO, metadata and buffers.
const rb_iseq_t * iseqptr
iseq pointer, should be separated from iseqval
void rb_nativethread_lock_lock(rb_nativethread_lock_t *lock)
Blocks until the current thread obtains a lock.
void rb_native_mutex_lock(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_lock.
void rb_native_mutex_initialize(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_initialize.
void rb_native_mutex_unlock(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_unlock.
void rb_nativethread_lock_unlock(rb_nativethread_lock_t *lock)
Releases a lock.
void rb_native_mutex_destroy(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_destroy.
void rb_nativethread_lock_initialize(rb_nativethread_lock_t *lock)
Fills the passed lock with an initial value.
void rb_nativethread_lock_destroy(rb_nativethread_lock_t *lock)
Destroys the passed mutex.
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
uintptr_t VALUE
Type that represents a Ruby object.
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.