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/jit.h"
81#include "internal/coverage.h"
82#include "internal/error.h"
83#include "internal/eval.h"
84#include "internal/gc.h"
85#include "internal/hash.h"
86#include "internal/io.h"
87#include "internal/object.h"
88#include "internal/proc.h"
90#include "internal/scheduler.h"
91#include "internal/signal.h"
92#include "internal/thread.h"
93#include "internal/time.h"
94#include "internal/warnings.h"
102#include "ractor_core.h"
107#include "ccan/list/list.h"
109#ifndef USE_NATIVE_THREAD_PRIORITY
110#define USE_NATIVE_THREAD_PRIORITY 0
111#define RUBY_THREAD_PRIORITY_MAX 3
112#define RUBY_THREAD_PRIORITY_MIN -3
115static VALUE rb_cThreadShield;
116static VALUE cThGroup;
118static VALUE sym_immediate;
119static VALUE sym_on_blocking;
120static VALUE sym_never;
122static uint32_t thread_default_quantum_ms = 100;
124#define THREAD_LOCAL_STORAGE_INITIALISED FL_USER13
125#define THREAD_LOCAL_STORAGE_INITIALISED_P(th) RB_FL_TEST_RAW((th), THREAD_LOCAL_STORAGE_INITIALISED)
128rb_thread_local_storage(
VALUE thread)
130 if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
138 SLEEP_DEADLOCKABLE = 0x01,
139 SLEEP_SPURIOUS_CHECK = 0x02,
140 SLEEP_ALLOW_SPURIOUS = 0x04,
141 SLEEP_NO_CHECKINTS = 0x08,
144static void sleep_forever(rb_thread_t *th,
unsigned int fl);
145static int sleep_hrtime(rb_thread_t *, rb_hrtime_t,
unsigned int fl);
147static void rb_thread_sleep_deadly_allow_spurious_wakeup(
VALUE blocker,
VALUE timeout, rb_hrtime_t end);
148static int rb_threadptr_dead(rb_thread_t *th);
149static void rb_check_deadlock(rb_ractor_t *r);
150static int rb_threadptr_pending_interrupt_empty_p(
const rb_thread_t *th);
151static const char *thread_status_name(rb_thread_t *th,
int detail);
152static int hrtime_update_expire(rb_hrtime_t *,
const rb_hrtime_t);
153NORETURN(
static void async_bug_fd(
const char *mesg,
int errno_arg,
int fd));
154MAYBE_UNUSED(
static int consume_communication_pipe(
int fd));
157static rb_internal_thread_specific_key_t specific_key_count;
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), true);
179#define THREAD_BLOCKING_END(th) \
180 thread_sched_to_running((sched), (th)); \
181 rb_ractor_thread_switch(th->ractor, th, false); \
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 RB_NOGVL_FAIL_FLAGS (RB_NOGVL_INTR_FAIL | RB_NOGVL_PENDING_INTR_FAIL)
194#define BLOCKING_REGION(th, exec, ubf, ubfarg, flags) do { \
195 struct rb_blocking_region_buffer __region; \
196 if (blocking_region_begin(th, &__region, (ubf), (ubfarg), flags) || \
198 !only_if_constant((flags) & RB_NOGVL_FAIL_FLAGS, TRUE)) { \
201 RB_VM_SAVE_MACHINE_CONTEXT(th); \
202 thread_sched_to_waiting(TH_SCHED(th), th, false); \
204 blocking_region_end(th, &__region); \
212#define RUBY_VM_CHECK_INTS_BLOCKING(ec) vm_check_ints_blocking(ec)
214vm_check_ints_blocking(rb_execution_context_t *ec)
216#ifdef RUBY_ASSERT_CRITICAL_SECTION
217 VM_ASSERT(ec->assert_critical_section_entered == 0);
220 rb_thread_t *th = rb_ec_thread_ptr(ec);
222 if (LIKELY(rb_threadptr_pending_interrupt_empty_p(th))) {
223 if (LIKELY(!RUBY_VM_INTERRUPTED_ANY(ec)))
return FALSE;
226 th->pending_interrupt_queue_checked = 0;
227 RUBY_VM_SET_INTERRUPT(ec);
230 int result = rb_threadptr_execute_interrupts(th, 1);
233 if (result || RUBY_VM_INTERRUPTED(ec)) {
235 if (scheduler !=
Qnil) {
244rb_vm_check_ints_blocking(rb_execution_context_t *ec)
246 return vm_check_ints_blocking(ec);
254#if defined(HAVE_POLL)
255# if defined(__linux__)
258# if defined(__FreeBSD_version) && __FreeBSD_version >= 1100000
261# define POLLERR_SET (POLLHUP | POLLERR)
266timeout_prepare(rb_hrtime_t **to, rb_hrtime_t *rel, rb_hrtime_t *end,
270 *rel = rb_timeval2hrtime(timeout);
271 *end = rb_hrtime_add(rb_hrtime_now(), *rel);
279MAYBE_UNUSED(NOINLINE(
static int thread_start_func_2(rb_thread_t *th,
VALUE *stack_start)));
280MAYBE_UNUSED(
static bool th_has_dedicated_nt(
const rb_thread_t *th));
281MAYBE_UNUSED(
static int waitfd_to_waiting_flag(
int wfd_event));
283#ifdef RB_THREAD_SCHED_NONE
286# include THREAD_IMPL_SRC
290# include "thread_sched.c"
297#ifndef BUSY_WAIT_SIGNALS
298# define BUSY_WAIT_SIGNALS (0)
302# define USE_EVENTFD (0)
305#include "thread_sync.c"
336 if (RUBY_VM_INTERRUPTED_ANY(th->ec)) {
341 RUBY_VM_CHECK_INTS(th->ec);
344 if (!rb_threadptr_pending_interrupt_empty_p(th)) {
350 }
while (!th->ec->raised_flag && RUBY_VM_INTERRUPTED_ANY(th->ec) &&
353 VM_ASSERT(th->unblock.func == NULL);
355 th->unblock.func = func;
356 th->unblock.arg = arg;
363unblock_function_clear(rb_thread_t *th)
366 th->unblock.func = 0;
371threadptr_set_interrupt_locked(rb_thread_t *th,
bool trap)
375 RUBY_DEBUG_LOG(
"th:%u trap:%d", rb_th_serial(th), trap);
378 RUBY_VM_SET_TRAP_INTERRUPT(th->ec);
381 RUBY_VM_SET_INTERRUPT(th->ec);
384 if (th->unblock.func != NULL) {
385 (th->unblock.func)(th->unblock.arg);
393threadptr_set_interrupt(rb_thread_t *th,
int trap)
397 threadptr_set_interrupt_locked(th, trap);
404rb_threadptr_interrupt(rb_thread_t *th)
406 RUBY_DEBUG_LOG(
"th:%u", rb_th_serial(th));
407 threadptr_set_interrupt(th,
false);
411threadptr_trap_interrupt(rb_thread_t *th)
413 threadptr_set_interrupt(th,
true);
417terminate_all(rb_ractor_t *r,
const rb_thread_t *main_thread)
421 ccan_list_for_each(&r->threads.set, th, lt_node) {
422 if (th != main_thread) {
423 RUBY_DEBUG_LOG(
"terminate start th:%u status:%s", rb_th_serial(th), thread_status_name(th, TRUE));
425 rb_threadptr_pending_interrupt_enque(th, RUBY_FATAL_THREAD_TERMINATED);
426 rb_threadptr_interrupt(th);
428 RUBY_DEBUG_LOG(
"terminate done th:%u status:%s", rb_th_serial(th), thread_status_name(th, TRUE));
431 RUBY_DEBUG_LOG(
"main thread th:%u", rb_th_serial(th));
437rb_threadptr_join_list_wakeup(rb_thread_t *thread)
439 while (thread->join_list) {
443 thread->join_list = join_list->next;
445 rb_thread_t *target_thread = join_list->thread;
447 if (target_thread->scheduler !=
Qnil && join_list->fiber) {
451 rb_threadptr_interrupt(target_thread);
453 switch (target_thread->status) {
455 case THREAD_STOPPED_FOREVER:
456 target_thread->status = THREAD_RUNNABLE;
466rb_threadptr_unlock_all_locking_mutexes(rb_thread_t *th)
468 while (th->keeping_mutexes) {
469 rb_mutex_t *mutex = th->keeping_mutexes;
474 VM_ASSERT(mutex->ec_serial);
475 const char *error_message = rb_mutex_unlock_th(mutex, th, 0);
476 if (error_message) rb_bug(
"invalid keeping_mutexes: %s", error_message);
481rb_thread_terminate_all(rb_thread_t *th)
483 rb_ractor_t *cr = th->ractor;
484 rb_execution_context_t *
volatile ec = th->ec;
485 volatile int sleeping = 0;
487 if (cr->threads.main != th) {
488 rb_bug(
"rb_thread_terminate_all: called by child thread (%p, %p)",
489 (
void *)cr->threads.main, (
void *)th);
493 rb_threadptr_unlock_all_locking_mutexes(th);
497 cr->threads.terminating =
true;
500 if (EC_EXEC_TAG() == TAG_NONE) {
502 RUBY_DEBUG_LOG(
"th:%u", rb_th_serial(th));
504 terminate_all(cr, th);
506 while (rb_ractor_living_thread_num(cr) > 1) {
507 rb_hrtime_t rel = RB_HRTIME_PER_SEC;
513 native_sleep(th, &rel);
514 RUBY_VM_CHECK_INTS_BLOCKING(ec);
532void rb_threadptr_root_fiber_terminate(rb_thread_t *th);
533static void threadptr_interrupt_exec_cleanup(rb_thread_t *th);
536thread_cleanup_func_before_exec(
void *th_ptr)
538 rb_thread_t *th = th_ptr;
539 th->status = THREAD_KILLED;
542 th->ec->machine.stack_start = th->ec->machine.stack_end = NULL;
544 threadptr_interrupt_exec_cleanup(th);
545 rb_threadptr_root_fiber_terminate(th);
549thread_cleanup_func(
void *th_ptr,
int atfork)
551 rb_thread_t *th = th_ptr;
553 th->locking_mutex =
Qfalse;
554 thread_cleanup_func_before_exec(th_ptr);
557 native_thread_destroy_atfork(th->nt);
575rb_thread_free_native_thread(
void *th_ptr)
577 rb_thread_t *th = th_ptr;
582 if (th->sched.context == NULL) {
583 native_thread_destroy_atfork(th->nt);
588static VALUE rb_threadptr_raise(rb_thread_t *,
int,
VALUE *);
592ruby_thread_init_stack(rb_thread_t *th,
void *local_in_parent_frame)
594 native_thread_init_stack(th, local_in_parent_frame);
598rb_vm_proc_local_ep(
VALUE proc)
600 const VALUE *ep = vm_proc_ep(proc);
603 return rb_vm_ep_local_ep(ep);
612 int argc,
const VALUE *argv,
int kw_splat,
VALUE passed_block_handler,
613 const rb_cref_t *cref);
616thread_do_start_proc(rb_thread_t *th)
618 VALUE args = th->invoke_arg.proc.args;
619 const VALUE *args_ptr;
621 VALUE procval = th->invoke_arg.proc.proc;
623 GetProcPtr(procval, proc);
624 const rb_cref_t *cref = rb_proc_refinements_cref_for_call(procval);
626 th->ec->errinfo =
Qnil;
627 th->ec->root_lep = rb_vm_proc_local_ep(procval);
628 th->ec->root_svar =
Qfalse;
630 vm_check_ints_blocking(th->ec);
632 if (th->invoke_type == thread_invoke_type_ractor_proc) {
633 VALUE self = rb_ractor_self(th->ractor);
634 th->thgroup = th->ractor->thgroup_default =
rb_obj_alloc(cThGroup);
639 rb_ractor_receive_parameters(th->ec, th->ractor, args_len, (
VALUE *)args_ptr);
640 vm_check_ints_blocking(th->ec);
642 return rb_vm_invoke_proc_with_self(
645 th->invoke_arg.proc.kw_splat,
646 VM_BLOCK_HANDLER_NONE,
656 th->invoke_arg.proc.args =
Qnil;
662 vm_check_ints_blocking(th->ec);
664 return rb_vm_invoke_proc(
667 th->invoke_arg.proc.kw_splat,
668 VM_BLOCK_HANDLER_NONE,
675thread_do_start(rb_thread_t *th)
677 native_set_thread_name(th);
680 switch (th->invoke_type) {
681 case thread_invoke_type_proc:
682 result = thread_do_start_proc(th);
685 case thread_invoke_type_ractor_proc:
686 result = thread_do_start_proc(th);
687 rb_ractor_atexit(th->ec, result);
690 case thread_invoke_type_func:
691 result = (*th->invoke_arg.func.func)(th->invoke_arg.func.arg);
694 case thread_invoke_type_none:
695 rb_bug(
"unreachable");
701void rb_ec_clear_current_thread_trace_func(
const rb_execution_context_t *ec);
704thread_start_func_2(rb_thread_t *th,
VALUE *stack_start)
706 RUBY_DEBUG_LOG(
"th:%u", rb_th_serial(th));
707 VM_ASSERT(th != th->vm->ractor.main_thread);
709 enum ruby_tag_type state;
711 rb_thread_t *ractor_main_th = th->ractor->threads.main;
714 if (rb_ractor_status_p(th->ractor, ractor_blocking)) {
717 rb_vm_ractor_blocking_cnt_dec(th->vm, th->ractor, __FILE__, __LINE__);
730 VM_ASSERT(UNDEF_P(th->value));
732 volatile int fiber_scheduler_closed = 0, event_thread_end_hooked = 0;
737 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
740 result = thread_do_start(th);
743 if (!fiber_scheduler_closed) {
744 fiber_scheduler_closed = 1;
748 if (!event_thread_end_hooked) {
749 event_thread_end_hooked = 1;
753 if (state == TAG_NONE) {
758 errinfo = th->ec->errinfo;
760 VALUE exc = rb_vm_make_jump_tag_but_local_jump(state,
Qundef);
761 if (!
NIL_P(exc)) errinfo = exc;
763 if (state == TAG_FATAL) {
764 if (th->invoke_type == thread_invoke_type_ractor_proc) {
765 rb_ractor_atexit(th->ec,
Qnil);
770 if (th->invoke_type == thread_invoke_type_ractor_proc) {
771 rb_ractor_atexit_exception(th->ec);
777 if (th->report_on_exception) {
778 VALUE mesg = rb_thread_to_s(th->self);
779 rb_str_cat_cstr(mesg,
" terminated with exception (report_on_exception is true):\n");
780 rb_write_error_str(mesg);
781 rb_ec_error_print(th->ec, errinfo);
784 if (th->invoke_type == thread_invoke_type_ractor_proc) {
785 rb_ractor_atexit_exception(th->ec);
788 if (th->vm->thread_abort_on_exception ||
800 VM_ASSERT(!UNDEF_P(th->value));
802 rb_threadptr_join_list_wakeup(th);
803 rb_threadptr_unlock_all_locking_mutexes(th);
805 if (th->invoke_type == thread_invoke_type_ractor_proc) {
806 rb_thread_terminate_all(th);
807 rb_ractor_teardown(th->ec);
810 th->status = THREAD_KILLED;
811 RUBY_DEBUG_LOG(
"killed th:%u", rb_th_serial(th));
813 if (th->vm->ractor.main_thread == th) {
819 rb_threadptr_raise(ractor_main_th, 1, &errinfo);
824 rb_ec_clear_current_thread_trace_func(th->ec);
827 if (th->locking_mutex !=
Qfalse) {
828 rb_bug(
"thread_start_func_2: locking_mutex must not be set (%p:%"PRIxVALUE
")",
829 (
void *)th, th->locking_mutex);
832 if (th->ractor->threads.terminating &&
833 th->ractor->threads.cnt <= 2 ) {
835 rb_threadptr_interrupt(ractor_main_th);
838 rb_check_deadlock(th->ractor);
840 rb_fiber_close(th->ec->fiber_ptr);
842 thread_cleanup_func(th, FALSE);
843 VM_ASSERT(th->ec->vm_stack == NULL);
848 if (th->invoke_type == thread_invoke_type_ractor_proc) {
849 rb_ractor_postmortem(th, &pf);
852#if defined(USE_MN_THREADS) && USE_MN_THREADS
853 if (th_has_coroutine(th)) {
855 rb_thread_wake_fence(th);
860 coroutine_thread_terminated(th);
861 rb_ractor_postmortem_free(&pf);
866 if (th->invoke_type == thread_invoke_type_ractor_proc) {
875 rb_vm_t *
const vm = th->vm;
876 rb_thread_sched_winding_begin(vm);
881 thread_sched_to_dead(TH_SCHED(th), th);
882 rb_ractor_living_threads_remove(th->ractor, th);
883 rb_ractor_postmortem_free(&pf);
885 rb_thread_sched_winding_end(vm);
888 rb_ractor_living_threads_remove(th->ractor, th);
889 thread_sched_to_dead(TH_SCHED(th), th);
896 enum thread_invoke_type type;
909static void thread_specific_storage_alloc(rb_thread_t *th);
914 rb_execution_context_t *ec = GET_EC();
915 rb_thread_t *th = rb_thread_ptr(thval), *current_th = rb_ec_thread_ptr(ec);
918 thread_specific_storage_alloc(th);
922 "can't start a new thread (frozen ThreadGroup)");
928 if (params->type != thread_invoke_type_ractor_proc) {
929 rb_fiber_inherit_storage(ec, th->ec->fiber_ptr);
932 switch (params->type) {
933 case thread_invoke_type_proc:
934 th->invoke_type = thread_invoke_type_proc;
935 th->invoke_arg.proc.args = params->args;
936 th->invoke_arg.proc.proc = params->proc;
940 case thread_invoke_type_ractor_proc:
941 th->invoke_type = thread_invoke_type_ractor_proc;
942 th->ractor = params->g;
943 th->ec->ractor_id = rb_ractor_id(th->ractor);
944 th->ec->serial = th->ractor->next_ec_serial++;
945 th->ractor->threads.main = th;
946 th->invoke_arg.proc.proc = params->proc;
951 case thread_invoke_type_func:
952 th->invoke_type = thread_invoke_type_func;
953 th->invoke_arg.func.func = params->fn;
954 th->invoke_arg.func.arg = (
void *)params->args;
958 rb_bug(
"unreachable");
961 th->priority = current_th->priority;
962 th->thgroup = current_th->thgroup;
964 if (th->invoke_type == thread_invoke_type_ractor_proc) {
968 th->pending_interrupt_queue = 0;
969 th->pending_interrupt_mask_stack = 0;
970 th->pending_interrupt_queue_checked = 0;
978 th->pending_interrupt_queue_checked = 0;
979 th->pending_interrupt_mask_stack =
rb_ary_dup(current_th->pending_interrupt_mask_stack);
980 RBASIC_CLEAR_CLASS(th->pending_interrupt_mask_stack);
983 RUBY_DEBUG_LOG(
"r:%"PRI_SERIALT_PREFIX
"u th:%u", rb_ractor_id(th->ractor), rb_th_serial(th));
985 rb_ractor_living_threads_insert(th->ractor, th);
987 if (th->invoke_type == thread_invoke_type_ractor_proc) {
992 enum ruby_tag_type state;
994 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
995 rb_ractor_setup_default_port(params->g);
996 rb_ractor_send_parameters(ec, params->g, params->args);
999 if (state != TAG_NONE) {
1000 th->status = THREAD_KILLED;
1001 rb_ractor_cancel_creation(params->g, th);
1002 EC_JUMP_TAG(ec, state);
1007 err = native_thread_create(th);
1009 th->status = THREAD_KILLED;
1010 if (th->invoke_type == thread_invoke_type_ractor_proc) {
1014 rb_ractor_cancel_creation(th->ractor, th);
1017 rb_ractor_living_threads_remove(th->ractor, th);
1024#define threadptr_initialized(th) ((th)->invoke_type != thread_invoke_type_none)
1047thread_s_new(
int argc,
VALUE *argv,
VALUE klass)
1050 VALUE thread = rb_thread_alloc(klass);
1052 if (GET_RACTOR()->threads.main->status == THREAD_KILLED) {
1057 th = rb_thread_ptr(thread);
1058 if (!threadptr_initialized(th)) {
1059 rb_raise(
rb_eThreadError,
"uninitialized thread - check '%"PRIsVALUE
"#initialize'",
1079 .type = thread_invoke_type_proc,
1083 return thread_create_core(rb_thread_alloc(klass), ¶ms);
1087threadptr_invoke_proc_location(rb_thread_t *th)
1089 if (th->invoke_type == thread_invoke_type_proc) {
1090 return rb_proc_location(th->invoke_arg.proc.proc);
1101 rb_thread_t *th = rb_thread_ptr(thread);
1106 else if (th->invoke_type != thread_invoke_type_none) {
1107 VALUE loc = threadptr_invoke_proc_location(th);
1110 "already initialized thread - %"PRIsVALUE
":%"PRIsVALUE,
1119 .type = thread_invoke_type_proc,
1123 return thread_create_core(thread, ¶ms);
1131 .type = thread_invoke_type_func,
1135 return thread_create_core(rb_thread_alloc(
rb_cThread), ¶ms);
1139create_ractor_alloc_thread(rb_ractor_t *r, rb_ractor_t *cr, rb_execution_context_t *ec)
1151 void *
const child_objspace = r->objspace;
1153 const bool multi_objspace = rb_gc_multi_objspace_p();
1154 enum ruby_tag_type alloc_state = TAG_NONE;
1156 if (multi_objspace) {
1158 cr->creating_child_objspace = child_objspace;
1162 VALUE gc_was_disabled = rb_gc_objspace_disable_no_rest(child_objspace);
1166 if ((alloc_state = EC_EXEC_TAG()) == TAG_NONE) {
1167 thval = rb_thread_alloc_in_objspace(
rb_cThread, child_objspace);
1170 if (gc_was_disabled ==
Qfalse) rb_gc_objspace_enable(child_objspace);
1171 if (alloc_state != TAG_NONE) {
1175 if (multi_objspace) cr->creating_child_objspace = NULL;
1177 rb_gc_objspace_disown(r->objspace);
1182 if (alloc_state != TAG_NONE) EC_JUMP_TAG(ec, alloc_state);
1187rb_thread_create_ractor(rb_ractor_t *r,
VALUE args,
VALUE proc)
1190 .type = thread_invoke_type_ractor_proc,
1196 rb_ractor_t *cr = GET_RACTOR();
1197 rb_execution_context_t *ec = GET_EC();
1199 VALUE thval = create_ractor_alloc_thread(r, cr, ec);
1205 enum ruby_tag_type state;
1208 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
1209 thret = thread_create_core(thval, ¶ms);
1212 if (state != TAG_NONE) {
1214 if (cr->creating_child_objspace == r->objspace) {
1215 cr->creating_child_objspace = NULL;
1218 rb_gc_objspace_disown(r->objspace);
1222 EC_JUMP_TAG(ec, state);
1230 rb_thread_t *target;
1236remove_from_join_list(
VALUE arg)
1239 rb_thread_t *target_thread = p->target;
1241 if (target_thread->status != THREAD_KILLED) {
1244 while (*join_list) {
1245 if (*join_list == p->waiter) {
1246 *join_list = (*join_list)->next;
1250 join_list = &(*join_list)->next;
1258thread_finished(rb_thread_t *th)
1260 return th->status == THREAD_KILLED || !UNDEF_P(th->value);
1264thread_join_sleep(
VALUE arg)
1267 rb_thread_t *target_th = p->target, *th = p->waiter->thread;
1268 rb_hrtime_t end = 0, *limit = p->limit;
1271 end = rb_hrtime_add(*limit, rb_hrtime_now());
1274 while (!thread_finished(target_th)) {
1278 if (scheduler !=
Qnil) {
1282 sleep_forever(th, SLEEP_DEADLOCKABLE | SLEEP_ALLOW_SPURIOUS | SLEEP_NO_CHECKINTS);
1286 if (hrtime_update_expire(limit, end)) {
1287 RUBY_DEBUG_LOG(
"timeout target_th:%u", rb_th_serial(target_th));
1291 if (scheduler !=
Qnil) {
1292 VALUE timeout = rb_float_new(hrtime2double(*limit));
1296 th->status = THREAD_STOPPED;
1297 native_sleep(th, limit);
1300 RUBY_VM_CHECK_INTS_BLOCKING(th->ec);
1301 th->status = THREAD_RUNNABLE;
1303 RUBY_DEBUG_LOG(
"interrupted target_th:%u status:%s", rb_th_serial(target_th), thread_status_name(target_th, TRUE));
1310thread_join(rb_thread_t *target_th,
VALUE timeout, rb_hrtime_t *limit)
1312 rb_execution_context_t *ec = GET_EC();
1313 rb_thread_t *th = ec->thread_ptr;
1314 rb_fiber_t *fiber = ec->fiber_ptr;
1316 if (th == target_th) {
1317 rb_raise(
rb_eThreadError,
"Target thread must not be current thread");
1320 if (th->ractor->threads.main == target_th) {
1324 RUBY_DEBUG_LOG(
"target_th:%u status:%s", rb_th_serial(target_th), thread_status_name(target_th, TRUE));
1326 if (target_th->status != THREAD_KILLED) {
1328 waiter.next = target_th->join_list;
1330 waiter.fiber = rb_fiberptr_blocking(fiber) ? NULL : fiber;
1331 target_th->join_list = &waiter;
1334 arg.waiter = &waiter;
1335 arg.target = target_th;
1336 arg.timeout = timeout;
1344 RUBY_DEBUG_LOG(
"success target_th:%u status:%s", rb_th_serial(target_th), thread_status_name(target_th, TRUE));
1346 if (target_th->ec->errinfo !=
Qnil) {
1347 VALUE err = target_th->ec->errinfo;
1352 RUBY_DEBUG_LOG(
"terminated target_th:%u status:%s", rb_th_serial(target_th), thread_status_name(target_th, TRUE));
1357 if (err == RUBY_FATAL_FIBER_KILLED) {
1361 rb_bug(
"thread_join: Fixnum (%d) should not reach here.",
FIX2INT(err));
1364 else if (THROW_DATA_P(target_th->ec->errinfo)) {
1365 rb_bug(
"thread_join: THROW_DATA should not reach here.");
1372 return target_th->self;
1415thread_join_m(
int argc,
VALUE *argv,
VALUE self)
1418 rb_hrtime_t rel = 0, *limit = 0;
1429 if (
NIL_P(timeout)) {
1433 rel = rb_sec2hrtime(NUM2TIMET(timeout));
1437 limit = double2hrtime(&rel,
rb_num2dbl(timeout));
1440 return thread_join(rb_thread_ptr(self), timeout, limit);
1458thread_value(
VALUE self)
1460 rb_thread_t *th = rb_thread_ptr(self);
1461 thread_join(th,
Qnil, 0);
1462 if (UNDEF_P(th->value)) {
1476#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
1477 if (clock_gettime(CLOCK_MONOTONIC, ts) == 0)
1487NOINLINE(rb_hrtime_t rb_hrtime_now(
void));
1494 return rb_timespec2hrtime(&ts);
1501COMPILER_WARNING_PUSH
1502#if defined(__GNUC__) && __GNUC__ == 7 && __GNUC_MINOR__ <= 3
1503COMPILER_WARNING_IGNORED(-Wmaybe-uninitialized)
1506#define PRIu64 PRI_64_PREFIX "u"
1514hrtime_update_expire(rb_hrtime_t *timeout,
const rb_hrtime_t end)
1516 rb_hrtime_t now = rb_hrtime_now();
1518 if (now > end)
return 1;
1520 RUBY_DEBUG_LOG(
"%"PRIu64
" > %"PRIu64
"", (uint64_t)end, (uint64_t)now);
1522 *timeout = end - now;
1527static int sleep_hrtime_until(rb_thread_t *th, rb_hrtime_t end,
unsigned int fl);
1530sleep_hrtime(rb_thread_t *th, rb_hrtime_t rel,
unsigned int fl)
1532 return sleep_hrtime_until(th, rb_hrtime_add(rb_hrtime_now(), rel), fl);
1536sleep_hrtime_until(rb_thread_t *th, rb_hrtime_t end,
unsigned int fl)
1538 enum rb_thread_status prev_status = th->status;
1540 rb_hrtime_t rel = rb_hrtime_sub(end, rb_hrtime_now());
1542 th->status = THREAD_STOPPED;
1543 RUBY_VM_CHECK_INTS_BLOCKING(th->ec);
1544 while (th->status == THREAD_STOPPED) {
1545 native_sleep(th, &rel);
1546 woke = vm_check_ints_blocking(th->ec);
1547 if (woke && !(fl & SLEEP_SPURIOUS_CHECK))
1549 if (hrtime_update_expire(&rel, end))
1553 th->status = prev_status;
1558sleep_forever(rb_thread_t *th,
unsigned int fl)
1560 enum rb_thread_status prev_status = th->status;
1561 enum rb_thread_status status;
1564 status = fl & SLEEP_DEADLOCKABLE ? THREAD_STOPPED_FOREVER : THREAD_STOPPED;
1565 th->status = status;
1567 if (!(fl & SLEEP_NO_CHECKINTS)) RUBY_VM_CHECK_INTS_BLOCKING(th->ec);
1569 while (th->status == status) {
1570 if (fl & SLEEP_DEADLOCKABLE) {
1571 rb_ractor_sleeper_threads_inc(th->ractor);
1572 rb_check_deadlock(th->ractor);
1575 native_sleep(th, 0);
1577 if (fl & SLEEP_DEADLOCKABLE) {
1578 rb_ractor_sleeper_threads_dec(th->ractor);
1580 if (fl & SLEEP_ALLOW_SPURIOUS) {
1584 woke = vm_check_ints_blocking(th->ec);
1586 if (woke && !(fl & SLEEP_SPURIOUS_CHECK)) {
1590 th->status = prev_status;
1596 RUBY_DEBUG_LOG(
"forever");
1597 sleep_forever(GET_THREAD(), SLEEP_SPURIOUS_CHECK);
1603 RUBY_DEBUG_LOG(
"deadly");
1604 sleep_forever(GET_THREAD(), SLEEP_DEADLOCKABLE|SLEEP_SPURIOUS_CHECK);
1608rb_thread_sleep_deadly_allow_spurious_wakeup(
VALUE blocker,
VALUE timeout, rb_hrtime_t end)
1610 rb_thread_t *th = GET_THREAD();
1612 if (scheduler !=
Qnil) {
1616 RUBY_DEBUG_LOG(
"...");
1618 sleep_hrtime_until(th, end, SLEEP_SPURIOUS_CHECK);
1621 sleep_forever(th, SLEEP_DEADLOCKABLE);
1629 rb_thread_t *th = GET_THREAD();
1631 sleep_hrtime(th, rb_timeval2hrtime(&time), SLEEP_SPURIOUS_CHECK);
1635rb_ec_check_ints(rb_execution_context_t *ec)
1637 RUBY_VM_CHECK_INTS_BLOCKING(ec);
1650 rb_ec_check_ints(GET_EC());
1658rb_thread_check_trap_pending(
void)
1660 return rb_signal_buff_size() != 0;
1667 return (
int)RUBY_VM_INTERRUPTED(rb_thread_ptr(thval)->ec);
1677rb_thread_schedule_limits(uint32_t limits_us)
1680 rb_thread_t *th = GET_THREAD();
1681 RUBY_DEBUG_LOG(
"us:%u", (
unsigned int)limits_us);
1683 if (th->running_time_us >= limits_us) {
1684 RUBY_DEBUG_LOG(
"switch %s",
"start");
1686 RB_VM_SAVE_MACHINE_CONTEXT(th);
1687 thread_sched_yield(TH_SCHED(th), th);
1688 rb_ractor_thread_switch(th->ractor, th,
true);
1690 RUBY_DEBUG_LOG(
"switch %s",
"done");
1698 rb_thread_schedule_limits(0);
1699 RUBY_VM_CHECK_INTS(GET_EC());
1708#ifdef RUBY_ASSERT_CRITICAL_SECTION
1709 VM_ASSERT(th->ec->assert_critical_section_entered == 0);
1711 VM_ASSERT(th == GET_THREAD());
1713 region->prev_status = th->status;
1714 if (unblock_function_set(th, ubf, arg, flags)) {
1715 th->blocking_region_buffer = region;
1716 th->status = THREAD_STOPPED;
1717 rb_ractor_blocking_threads_inc(th->ractor, __FILE__, __LINE__);
1719 RUBY_DEBUG_LOG(
"thread_id:%p", (
void *)th->nt->thread_id);
1731 unblock_function_clear(th);
1733 unregister_ubf_list(th);
1735 thread_sched_to_running(TH_SCHED(th), th);
1736 rb_ractor_thread_switch(th->ractor, th,
false);
1738 th->blocking_region_buffer = 0;
1739 rb_ractor_blocking_threads_dec(th->ractor, __FILE__, __LINE__);
1740 if (th->status == THREAD_STOPPED) {
1741 th->status = region->prev_status;
1744 RUBY_DEBUG_LOG(
"end");
1748 VM_ASSERT(th == GET_THREAD());
1768 *unblock_function = ubf_select;
1776rb_nogvl(
void *(*func)(
void *),
void *data1,
1780 rb_execution_context_t *ec = GET_EC();
1781 rb_thread_t *th = rb_ec_thread_ptr(ec);
1785 !rb_threadptr_pending_interrupt_empty_p(th)
1795 if (scheduler !=
Qnil) {
1800 if (!UNDEF_P(result)) {
1801 rb_errno_set(state.saved_errno);
1802 return state.result;
1808 rb_vm_t *vm = rb_ec_vm_ptr(ec);
1809 bool is_main_thread = vm->ractor.main_thread == th;
1810 int saved_errno = 0;
1812 bool sentinel_ubf = rb_thread_resolve_unblock_function(&ubf, &data2, th);
1814 if (ubf && rb_ractor_living_thread_num(th->ractor) == 1 && is_main_thread) {
1819 vm->ubf_async_safe = 1;
1823 rb_vm_t *
volatile saved_vm = vm;
1824 BLOCKING_REGION(th, {
1827 }, ubf, data2, flags);
1830 if (is_main_thread) vm->ubf_async_safe = 0;
1833 RUBY_VM_CHECK_INTS_BLOCKING(ec);
1836 rb_errno_set(saved_errno);
1937 return rb_nogvl(func, data1, ubf, data2, 0);
1941waitfd_to_waiting_flag(
int wfd_event)
1943 return wfd_event << 1;
1946static struct ccan_list_head *
1947rb_io_blocking_operations(
struct rb_io *io)
1949 rb_serial_t fork_generation = GET_VM()->fork_gen;
1953 if (io->fork_generation != fork_generation) {
1955 io->fork_generation = fork_generation;
1974 ccan_list_add(rb_io_blocking_operations(io), &blocking_operation->list);
1980 ccan_list_del(&blocking_operation->list);
1989io_blocking_operation_exit(
VALUE _arguments)
1994 rb_io_blocking_operation_pop(arguments->io, blocking_operation);
1996 rb_io_t *io = arguments->io;
1997 rb_thread_t *thread = io->closing_ec->thread_ptr;
1998 rb_fiber_t *fiber = io->closing_ec->fiber_ptr;
2000 if (thread->scheduler !=
Qnil) {
2024 VALUE wakeup_mutex = io->wakeup_mutex;
2027 blocking_operation->ec = NULL;
2029 if (!
NIL_P(blocking_operation->scheduler_interrupt_target)) {
2030 rb_fiber_scheduler_interrupt_target_invalidate(blocking_operation->scheduler_interrupt_target);
2036 .blocking_operation = blocking_operation
2043 rb_io_blocking_operation_pop(io, blocking_operation);
2048rb_thread_io_blocking_operation_ensure(
VALUE _argument)
2052 rb_io_blocking_operation_exit(arguments->io, arguments->blocking_operation);
2064rb_thread_io_blocking_operation_body(
VALUE _arguments)
2067 VALUE result = arguments->function(arguments->argument);
2068 VALUE target = arguments->blocking_operation->scheduler_interrupt_target;
2070 if (!
NIL_P(target)) {
2071 VALUE exception = rb_fiber_scheduler_interrupt_target_exception(target);
2073 if (!
NIL_P(exception)) {
2100 rb_execution_context_t *ec = GET_EC();
2103 .scheduler_interrupt_target =
Qnil,
2105 rb_io_blocking_operation_enter(io, &blocking_operation);
2109 .blocking_operation = &blocking_operation
2113 .function = function,
2114 .argument = argument,
2115 .blocking_operation = &blocking_operation,
2122thread_io_mn_schedulable(rb_thread_t *th,
int events,
const struct timeval *timeout)
2124#if defined(USE_MN_THREADS) && USE_MN_THREADS
2128 return !th_has_dedicated_nt(th) && (events || timeout) && th->blocking &&
2129 !(events & ~(RB_WAITFD_IN | RB_WAITFD_OUT));
2135enum io_wait_result {
2139 io_wait_interrupted,
2145static enum io_wait_result
2146thread_io_wait_events(rb_thread_t *th,
int fd,
int events,
const struct timeval *timeout,
2147 bool known_not_ready)
2149#if defined(USE_MN_THREADS) && USE_MN_THREADS
2150 if (thread_io_mn_schedulable(th, events, timeout)) {
2151 rb_hrtime_t rel, *prel;
2154 rel = rb_timeval2hrtime(timeout);
2161 VM_ASSERT(prel || (events & (RB_WAITFD_IN | RB_WAITFD_OUT)));
2163 enum thread_sched_waiting_flag flags = waitfd_to_waiting_flag(events);
2164 if (known_not_ready) flags |= thread_sched_waiting_io_force;
2166 switch (thread_sched_wait_events(TH_SCHED(th), th, fd, flags, prel)) {
2167 case thread_sched_wait_event:
2168 return io_wait_ready;
2169 case thread_sched_wait_timeout:
2170 return io_wait_timed_out;
2171 case thread_sched_wait_unavailable:
2174 return io_wait_unhandled;
2175 case thread_sched_wait_interrupted:
2176 return io_wait_interrupted;
2180 return io_wait_unhandled;
2185blocking_call_retryable_p(
int r,
int eno)
2187 if (r != -1)
return false;
2191#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
2201rb_thread_mn_schedulable(
VALUE thval)
2203 rb_thread_t *th = rb_thread_ptr(thval);
2204 return th->mn_schedulable;
2208rb_thread_io_blocking_call(
struct rb_io* io, rb_blocking_function_t *func,
void *data1,
int events)
2210 rb_execution_context_t *
volatile ec = GET_EC();
2211 rb_thread_t *
volatile th = rb_ec_thread_ptr(ec);
2213 RUBY_DEBUG_LOG(
"th:%u fd:%d ev:%d", rb_th_serial(th), io->
fd, events);
2216 volatile int saved_errno = 0;
2217 enum ruby_tag_type state;
2218 volatile bool prev_mn_schedulable = th->mn_schedulable;
2219 th->mn_schedulable = thread_io_mn_schedulable(th, events, NULL);
2225 .scheduler_interrupt_target =
Qnil,
2227 rb_io_blocking_operation_enter(io, &blocking_operation);
2231 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
2232 volatile enum ruby_tag_type saved_state = state;
2234 BLOCKING_REGION(th, {
2241 saved_errno =
errno;
2242 }, ubf_select, th, FALSE);
2245 if (events && blocking_call_retryable_p((
int)val, saved_errno)) {
2248 if (thread_io_wait_events(th, fd, events, NULL,
true) != io_wait_unhandled) {
2249 RUBY_VM_CHECK_INTS_BLOCKING(ec);
2252 else if (th->mn_schedulable) {
2255 rb_thread_wait_for_single_fd(th, fd, events, NULL);
2256 RUBY_VM_CHECK_INTS_BLOCKING(ec);
2261 RUBY_VM_CHECK_INTS_BLOCKING(ec);
2263 state = saved_state;
2267 th = rb_ec_thread_ptr(ec);
2268 th->mn_schedulable = prev_mn_schedulable;
2271 rb_io_blocking_operation_exit(io, &blocking_operation);
2274 EC_JUMP_TAG(ec, state);
2278 if (saved_errno == ETIMEDOUT) {
2282 errno = saved_errno;
2288rb_thread_io_blocking_region(
struct rb_io *io, rb_blocking_function_t *func,
void *data1)
2290 return rb_thread_io_blocking_call(io, func, data1, 0);
2327 rb_thread_t *th = ruby_thread_from_native();
2338 fprintf(stderr,
"[BUG] rb_thread_call_with_gvl() is called by non-ruby thread\n");
2343 prev_unblock = th->unblock;
2347 return (*func)(data1);
2350 blocking_region_end(th, brb);
2354 int released = blocking_region_begin(th, brb, prev_unblock.func, prev_unblock.arg, FALSE);
2356 RB_VM_SAVE_MACHINE_CONTEXT(th);
2357 thread_sched_to_waiting(TH_SCHED(th), th,
true);
2368 rb_thread_t *th = ruby_thread_from_native();
2370 if (th && th->blocking_region_buffer == 0) {
2387thread_s_pass(
VALUE klass)
2412rb_threadptr_pending_interrupt_clear(rb_thread_t *th)
2418rb_threadptr_pending_interrupt_enque(rb_thread_t *th,
VALUE v)
2421 th->pending_interrupt_queue_checked = 0;
2425threadptr_check_pending_interrupt_queue(rb_thread_t *th)
2427 if (!th->pending_interrupt_queue) {
2432enum handle_interrupt_timing {
2434 INTERRUPT_IMMEDIATE,
2435 INTERRUPT_ON_BLOCKING,
2439static enum handle_interrupt_timing
2440rb_threadptr_pending_interrupt_from_symbol(rb_thread_t *th,
VALUE sym)
2442 if (sym == sym_immediate) {
2443 return INTERRUPT_IMMEDIATE;
2445 else if (sym == sym_on_blocking) {
2446 return INTERRUPT_ON_BLOCKING;
2448 else if (sym == sym_never) {
2449 return INTERRUPT_NEVER;
2456static enum handle_interrupt_timing
2457rb_threadptr_pending_interrupt_check_mask(rb_thread_t *th,
VALUE err)
2465 for (i=0; i<mask_stack_len; i++) {
2466 mask = mask_stack[mask_stack_len-(i+1)];
2471 return rb_threadptr_pending_interrupt_from_symbol(th, mask);
2483 klass =
RBASIC(mod)->klass;
2485 else if (mod != RCLASS_ORIGIN(mod)) {
2489 if ((sym = rb_hash_aref(mask, klass)) !=
Qnil) {
2490 return rb_threadptr_pending_interrupt_from_symbol(th, sym);
2495 return INTERRUPT_NONE;
2499rb_threadptr_pending_interrupt_empty_p(
const rb_thread_t *th)
2501 return RARRAY_LEN(th->pending_interrupt_queue) == 0;
2505rb_threadptr_pending_interrupt_include_p(rb_thread_t *th,
VALUE err)
2508 for (i=0; i<
RARRAY_LEN(th->pending_interrupt_queue); i++) {
2518rb_threadptr_pending_interrupt_deque(rb_thread_t *th,
enum handle_interrupt_timing timing)
2523 for (i=0; i<
RARRAY_LEN(th->pending_interrupt_queue); i++) {
2526 enum handle_interrupt_timing mask_timing = rb_threadptr_pending_interrupt_check_mask(th,
CLASS_OF(err));
2528 switch (mask_timing) {
2529 case INTERRUPT_ON_BLOCKING:
2530 if (timing != INTERRUPT_ON_BLOCKING) {
2534 case INTERRUPT_NONE:
2535 case INTERRUPT_IMMEDIATE:
2538 case INTERRUPT_NEVER:
2543 th->pending_interrupt_queue_checked = 1;
2547 if (rb_threadptr_pending_interrupt_empty_p(th)) {
2548 th->pending_interrupt_queue_checked = 1;
2555threadptr_pending_interrupt_active_p(rb_thread_t *th)
2562 if (th->pending_interrupt_queue_checked) {
2566 if (rb_threadptr_pending_interrupt_empty_p(th)) {
2578 if (val != sym_immediate && val != sym_on_blocking && val != sym_never) {
2579 rb_raise(rb_eArgError,
"unknown mask signature");
2587 if (
RTEST(*maskp)) {
2589 VALUE prev = *maskp;
2590 *maskp = rb_ident_hash_new();
2595 rb_hash_aset(*maskp, key, val);
2689rb_thread_s_handle_interrupt(
VALUE self,
VALUE mask_arg)
2692 rb_execution_context_t *
volatile ec = GET_EC();
2693 rb_thread_t *
volatile th = rb_ec_thread_ptr(ec);
2695 enum ruby_tag_type state;
2698 rb_raise(rb_eArgError,
"block is needed.");
2701 mask_arg = rb_to_hash_type(mask_arg);
2703 if (
OBJ_FROZEN(mask_arg) && rb_hash_compare_by_id_p(mask_arg)) {
2709 if (UNDEF_P(mask)) {
2720 rb_ary_push(th->pending_interrupt_mask_stack, mask);
2721 if (!rb_threadptr_pending_interrupt_empty_p(th)) {
2722 th->pending_interrupt_queue_checked = 0;
2723 RUBY_VM_SET_INTERRUPT(th->ec);
2726 EC_PUSH_TAG(th->ec);
2727 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
2732 rb_ary_pop(th->pending_interrupt_mask_stack);
2733 if (!rb_threadptr_pending_interrupt_empty_p(th)) {
2734 th->pending_interrupt_queue_checked = 0;
2735 RUBY_VM_SET_INTERRUPT(th->ec);
2738 RUBY_VM_CHECK_INTS(th->ec);
2741 EC_JUMP_TAG(th->ec, state);
2758rb_thread_pending_interrupt_p(
int argc,
VALUE *argv,
VALUE target_thread)
2760 rb_thread_t *target_th = rb_thread_ptr(target_thread);
2762 if (!target_th->pending_interrupt_queue) {
2765 if (rb_threadptr_pending_interrupt_empty_p(target_th)) {
2769 VALUE err = argv[0];
2771 rb_raise(
rb_eTypeError,
"class or module required for rescue clause");
2773 return RBOOL(rb_threadptr_pending_interrupt_include_p(target_th, err));
2838rb_thread_s_pending_interrupt_p(
int argc,
VALUE *argv,
VALUE self)
2840 return rb_thread_pending_interrupt_p(argc, argv, GET_THREAD()->self);
2843NORETURN(
static void rb_threadptr_to_kill(rb_thread_t *th));
2846rb_threadptr_to_kill(rb_thread_t *th)
2848 VM_ASSERT(GET_THREAD() == th);
2849 rb_threadptr_pending_interrupt_clear(th);
2850 th->status = THREAD_RUNNABLE;
2852 th->ec->errinfo =
INT2FIX(TAG_FATAL);
2853 EC_JUMP_TAG(th->ec, TAG_FATAL);
2857threadptr_get_interrupts(rb_thread_t *th)
2859 rb_execution_context_t *ec = th->ec;
2863 old = ATOMIC_LOAD_RELAXED(ec->interrupt_flag);
2866 old = ATOMIC_CAS(ec->interrupt_flag, interrupt, interrupt & ec->interrupt_mask);
2867 }
while (old != interrupt);
2868 return interrupt & (
rb_atomic_t)~ec->interrupt_mask;
2871static void threadptr_interrupt_exec_exec(rb_thread_t *th);
2879rb_threadptr_execute_interrupts(rb_thread_t *th,
int blocking_timing)
2882 int postponed_job_interrupt = 0;
2885 VM_ASSERT(GET_THREAD() == th);
2887 if (th->ec->raised_flag)
return ret;
2892 const VALUE saved_errinfo = th->ec->errinfo;
2894 while ((interrupt = threadptr_get_interrupts(th)) != 0) {
2896 int timer_interrupt;
2897 int pending_interrupt;
2899 int terminate_interrupt;
2901 timer_interrupt = interrupt & TIMER_INTERRUPT_MASK;
2902 pending_interrupt = interrupt & PENDING_INTERRUPT_MASK;
2903 postponed_job_interrupt = interrupt & POSTPONED_JOB_INTERRUPT_MASK;
2904 trap_interrupt = interrupt & TRAP_INTERRUPT_MASK;
2905 terminate_interrupt = interrupt & TERMINATE_INTERRUPT_MASK;
2907 if (interrupt & VM_BARRIER_INTERRUPT_MASK) {
2911 if (postponed_job_interrupt) {
2912 rb_postponed_job_flush();
2915 if (trap_interrupt) {
2917 if (th == th->vm->ractor.main_thread) {
2918 enum rb_thread_status prev_status = th->status;
2920 th->status = THREAD_RUNNABLE;
2922 while ((sig = rb_get_next_signal()) != 0) {
2923 ret |= rb_signal_exec(th, sig);
2926 th->status = prev_status;
2929 if (!ccan_list_empty(&th->interrupt_exec_tasks)) {
2930 enum rb_thread_status prev_status = th->status;
2932 th->status = THREAD_RUNNABLE;
2934 threadptr_interrupt_exec_exec(th);
2936 th->status = prev_status;
2941 if (pending_interrupt && threadptr_pending_interrupt_active_p(th)) {
2942 VALUE err = rb_threadptr_pending_interrupt_deque(th, blocking_timing ? INTERRUPT_ON_BLOCKING : INTERRUPT_NONE);
2943 RUBY_DEBUG_LOG(
"err:%"PRIdVALUE, err);
2949 else if (err == RUBY_FATAL_THREAD_KILLED ||
2950 err == RUBY_FATAL_THREAD_TERMINATED ||
2952 terminate_interrupt = 1;
2955 if (err == th->vm->special_exceptions[ruby_error_stream_closed]) {
2957 err = ruby_vm_special_exception_copy(err);
2960 if (th->status == THREAD_STOPPED ||
2961 th->status == THREAD_STOPPED_FOREVER)
2962 th->status = THREAD_RUNNABLE;
2967 if (terminate_interrupt) {
2968 rb_threadptr_to_kill(th);
2971 if (timer_interrupt) {
2972 uint32_t limits_us = thread_default_quantum_ms * 1000;
2974 if (th->priority > 0)
2975 limits_us <<= th->priority;
2977 limits_us >>= -th->priority;
2979 if (th->status == THREAD_RUNNABLE)
2980 th->running_time_us += 10 * 1000;
2982 VM_ASSERT(th->ec->cfp);
2986 rb_thread_schedule_limits(limits_us);
2990 th->ec->errinfo = saved_errinfo;
2996rb_thread_execute_interrupts(
VALUE thval)
2998 rb_threadptr_execute_interrupts(rb_thread_ptr(thval), 1);
3002rb_threadptr_ready(rb_thread_t *th)
3004 rb_threadptr_interrupt(th);
3008rb_threadptr_raise(rb_thread_t *target_th,
int argc,
VALUE *argv)
3012 if (rb_threadptr_dead(target_th)) {
3020 exc = rb_make_exception(argc, argv);
3025 if (rb_threadptr_dead(target_th)) {
3029 rb_ec_setup_exception(GET_EC(), exc,
Qundef);
3030 rb_threadptr_pending_interrupt_enque(target_th, exc);
3031 rb_threadptr_interrupt(target_th);
3037rb_threadptr_signal_raise(rb_thread_t *th,
int sig)
3043 rb_threadptr_raise(th->vm->ractor.main_thread, 2, argv);
3047rb_threadptr_interrupt_raise(rb_thread_t *th)
3049 rb_thread_t *target_th = th->vm->ractor.main_thread;
3051 if (rb_threadptr_dead(target_th)) {
3060 if (rb_threadptr_dead(target_th)) {
3064 rb_ec_setup_exception(GET_EC(), exc,
Qundef);
3065 rb_threadptr_pending_interrupt_enque(target_th, exc);
3066 rb_threadptr_interrupt(target_th);
3070rb_threadptr_signal_exit(rb_thread_t *th)
3078 rb_threadptr_raise(th->vm->ractor.main_thread, 2, argv);
3082rb_ec_set_raised(rb_execution_context_t *ec)
3084 if (ec->raised_flag & RAISED_EXCEPTION) {
3087 ec->raised_flag |= RAISED_EXCEPTION;
3092rb_ec_reset_raised(rb_execution_context_t *ec)
3094 if (!(ec->raised_flag & RAISED_EXCEPTION)) {
3097 ec->raised_flag &= ~RAISED_EXCEPTION;
3122thread_io_close_notify_all(
VALUE _io)
3127 rb_vm_t *vm = io->closing_ec->thread_ptr->vm;
3128 VALUE error = vm->special_exceptions[ruby_error_stream_closed];
3131 ccan_list_for_each(rb_io_blocking_operations(io), blocking_operation, list) {
3132 rb_execution_context_t *ec = blocking_operation->ec;
3136 rb_thread_t *thread = ec->thread_ptr;
3138 if (thread->scheduler !=
Qnil) {
3139 VALUE target = blocking_operation->scheduler_interrupt_target;
3141 if (
NIL_P(target)) {
3142 VALUE fiber = rb_fiberptr_self(ec->fiber_ptr);
3143 target = rb_fiber_scheduler_interrupt_target_new(fiber, error);
3144 blocking_operation->scheduler_interrupt_target = target;
3152 rb_threadptr_pending_interrupt_enque(thread, error);
3153 rb_threadptr_interrupt(thread);
3160 return (
VALUE)count;
3164rb_thread_io_close_interrupt(
struct rb_io *io)
3167 if (io->closing_ec) {
3172 if (ccan_list_empty(rb_io_blocking_operations(io))) {
3177 rb_execution_context_t *ec = GET_EC();
3178 io->closing_ec = ec;
3182 rb_mutex_allow_trap(io->wakeup_mutex, 1);
3187 return (
size_t)result;
3191rb_thread_io_close_wait(
struct rb_io* io)
3193 VALUE wakeup_mutex = io->wakeup_mutex;
3201 while (!ccan_list_empty(rb_io_blocking_operations(io))) {
3207 io->wakeup_mutex =
Qnil;
3208 io->closing_ec = NULL;
3214 rb_warn(
"rb_thread_fd_close is deprecated (and is now a no-op).");
3238thread_raise_m(
int argc,
VALUE *argv,
VALUE self)
3240 rb_thread_t *target_th = rb_thread_ptr(self);
3241 const rb_thread_t *current_th = GET_THREAD();
3243 threadptr_check_pending_interrupt_queue(target_th);
3245 if (rb_threadptr_dead(target_th)) {
3249 VALUE exception = rb_exception_setup(argc, argv);
3250 rb_threadptr_pending_interrupt_enque(target_th, exception);
3251 rb_threadptr_interrupt(target_th);
3254 if (current_th == target_th) {
3255 RUBY_VM_CHECK_INTS(target_th->ec);
3278 rb_thread_t *target_th = rb_thread_ptr(thread);
3280 if (target_th->to_kill || target_th->status == THREAD_KILLED) {
3283 if (target_th == target_th->vm->ractor.main_thread) {
3287 RUBY_DEBUG_LOG(
"target_th:%u", rb_th_serial(target_th));
3289 if (target_th == GET_THREAD()) {
3291 rb_threadptr_to_kill(target_th);
3294 threadptr_check_pending_interrupt_queue(target_th);
3295 rb_threadptr_pending_interrupt_enque(target_th, RUBY_FATAL_THREAD_KILLED);
3296 rb_threadptr_interrupt(target_th);
3303rb_thread_to_be_killed(
VALUE thread)
3305 rb_thread_t *target_th = rb_thread_ptr(thread);
3307 if (target_th->to_kill || target_th->status == THREAD_KILLED) {
3349 rb_thread_t *th = GET_THREAD();
3382 rb_thread_t *target_th = rb_thread_ptr(thread);
3383 if (target_th->status == THREAD_KILLED)
return Qnil;
3385 rb_threadptr_ready(target_th);
3387 if (target_th->status == THREAD_STOPPED ||
3388 target_th->status == THREAD_STOPPED_FOREVER) {
3389 target_th->status = THREAD_RUNNABLE;
3431 "stopping only thread\n\tnote: use sleep to stop forever");
3464 return rb_ractor_thread_list();
3490 return rb_thread_list();
3496 return GET_THREAD()->self;
3509thread_s_current(
VALUE klass)
3517 return GET_RACTOR()->threads.main->self;
3528rb_thread_s_main(
VALUE klass)
3555rb_thread_s_abort_exc(
VALUE _)
3557 return RBOOL(GET_THREAD()->vm->thread_abort_on_exception);
3592rb_thread_s_abort_exc_set(
VALUE self,
VALUE val)
3594 GET_THREAD()->vm->thread_abort_on_exception =
RTEST(val);
3615rb_thread_abort_exc(
VALUE thread)
3617 return RBOOL(rb_thread_ptr(thread)->abort_on_exception);
3635rb_thread_abort_exc_set(
VALUE thread,
VALUE val)
3637 rb_thread_ptr(thread)->abort_on_exception =
RTEST(val);
3685rb_thread_s_report_exc(
VALUE _)
3687 return RBOOL(GET_THREAD()->vm->thread_report_on_exception);
3722rb_thread_s_report_exc_set(
VALUE self,
VALUE val)
3724 GET_THREAD()->vm->thread_report_on_exception =
RTEST(val);
3741rb_thread_s_ignore_deadlock(
VALUE _)
3743 return RBOOL(GET_THREAD()->vm->thread_ignore_deadlock);
3768rb_thread_s_ignore_deadlock_set(
VALUE self,
VALUE val)
3770 GET_THREAD()->vm->thread_ignore_deadlock =
RTEST(val);
3792rb_thread_report_exc(
VALUE thread)
3794 return RBOOL(rb_thread_ptr(thread)->report_on_exception);
3812rb_thread_report_exc_set(
VALUE thread,
VALUE val)
3814 rb_thread_ptr(thread)->report_on_exception =
RTEST(val);
3829rb_thread_group(
VALUE thread)
3831 return rb_thread_ptr(thread)->thgroup;
3835thread_status_name(rb_thread_t *th,
int detail)
3837 switch (th->status) {
3838 case THREAD_RUNNABLE:
3839 return th->to_kill ?
"aborting" :
"run";
3840 case THREAD_STOPPED_FOREVER:
3841 if (detail)
return "sleep_forever";
3842 case THREAD_STOPPED:
3852rb_threadptr_dead(rb_thread_t *th)
3854 return th->status == THREAD_KILLED;
3890rb_thread_status(
VALUE thread)
3892 rb_thread_t *target_th = rb_thread_ptr(thread);
3894 if (rb_threadptr_dead(target_th)) {
3895 if (!
NIL_P(target_th->ec->errinfo) &&
3896 !
FIXNUM_P(target_th->ec->errinfo)) {
3904 return rb_str_new2(thread_status_name(target_th, FALSE));
3924rb_thread_alive_p(
VALUE thread)
3926 return RBOOL(!thread_finished(rb_thread_ptr(thread)));
3944rb_thread_stop_p(
VALUE thread)
3946 rb_thread_t *th = rb_thread_ptr(thread);
3948 if (rb_threadptr_dead(th)) {
3951 return RBOOL(th->status == THREAD_STOPPED || th->status == THREAD_STOPPED_FOREVER);
3962rb_thread_getname(
VALUE thread)
3964 return rb_thread_ptr(thread)->name;
3978 rb_thread_t *target_th = rb_thread_ptr(thread);
3983 enc = rb_enc_get(name);
3984 if (!rb_enc_asciicompat(enc)) {
3985 rb_raise(rb_eArgError,
"ASCII incompatible encoding (%s)",
3990 target_th->name = name;
3991 if (threadptr_initialized(target_th) && target_th->has_dedicated_nt &&
3992 target_th->status != THREAD_KILLED) {
3993 native_set_another_thread_name(ACCESS_ONCE(rb_nativethread_id_t, target_th->nt->thread_id), name);
3998#if USE_NATIVE_THREAD_NATIVE_THREAD_ID
4022rb_thread_native_thread_id(
VALUE thread)
4024 rb_thread_t *target_th = rb_thread_ptr(thread);
4025 if (rb_threadptr_dead(target_th))
return Qnil;
4026 return native_thread_native_thread_id(target_th);
4029# define rb_thread_native_thread_id rb_f_notimplement
4040rb_thread_to_s(
VALUE thread)
4043 rb_thread_t *target_th = rb_thread_ptr(thread);
4047 status = thread_status_name(target_th, TRUE);
4048 str = rb_sprintf(
"#<%"PRIsVALUE
":%p", cname, (
void *)thread);
4049 if (!
NIL_P(target_th->name)) {
4050 rb_str_catf(str,
"@%"PRIsVALUE, target_th->name);
4052 if ((loc = threadptr_invoke_proc_location(target_th)) !=
Qnil) {
4053 rb_str_catf(str,
" %"PRIsVALUE
":%"PRIsVALUE,
4056 rb_str_catf(str,
" %s>", status);
4062#define recursive_key id__recursive_key__
4065threadptr_local_aref(rb_thread_t *th,
ID id)
4067 if (
id == recursive_key) {
4068 return th->ec->local_storage_recursive_hash;
4072 struct rb_id_table *local_storage = th->ec->local_storage;
4074 if (local_storage != NULL && rb_id_table_lookup(local_storage,
id, &val)) {
4086 return threadptr_local_aref(rb_thread_ptr(thread),
id);
4153 if (!
id)
return Qnil;
4171rb_thread_fetch(
int argc,
VALUE *argv,
VALUE self)
4175 rb_thread_t *target_th = rb_thread_ptr(self);
4182 if (block_given && argc == 2) {
4183 rb_warn(
"block supersedes default value argument");
4188 if (
id == recursive_key) {
4189 return target_th->ec->local_storage_recursive_hash;
4191 else if (
id && target_th->ec->local_storage &&
4192 rb_id_table_lookup(target_th->ec->local_storage,
id, &val)) {
4195 else if (block_given) {
4198 else if (argc == 1) {
4199 rb_key_err_raise(rb_sprintf(
"key not found: %+"PRIsVALUE, key), self, key);
4207threadptr_local_aset(rb_thread_t *th,
ID id,
VALUE val)
4209 if (
id == recursive_key) {
4210 th->ec->local_storage_recursive_hash = val;
4214 struct rb_id_table *local_storage = th->ec->local_storage;
4217 if (!local_storage)
return Qnil;
4218 rb_id_table_delete(local_storage,
id);
4222 if (local_storage == NULL) {
4223 th->ec->local_storage = local_storage = rb_id_table_create(0);
4225 rb_id_table_insert(local_storage,
id, val);
4238 return threadptr_local_aset(rb_thread_ptr(thread),
id, val);
4290rb_thread_variable_get(
VALUE thread,
VALUE key)
4295 if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
4298 locals = rb_thread_local_storage(thread);
4299 return rb_hash_aref(locals, symbol);
4325 if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
4329 locals = rb_thread_local_storage(thread);
4330 rb_hash_delete(locals, symbol);
4334 locals = rb_thread_local_storage(thread);
4335 return rb_hash_aset(locals, symbol, val);
4356 struct rb_id_table *local_storage = rb_thread_ptr(self)->ec->local_storage;
4358 if (!
id || local_storage == NULL) {
4361 return RBOOL(rb_id_table_lookup(local_storage,
id, &val));
4364static enum rb_id_table_iterator_result
4365thread_keys_i(
ID key,
VALUE value,
void *ary)
4368 return ID_TABLE_CONTINUE;
4375 return rb_ractor_living_thread_num(GET_RACTOR()) == 1;
4393rb_thread_keys(
VALUE self)
4395 struct rb_id_table *local_storage = rb_thread_ptr(self)->ec->local_storage;
4398 if (local_storage) {
4399 rb_id_table_foreach(local_storage, thread_keys_i, (
void *)ary);
4429rb_thread_variables(
VALUE thread)
4435 if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
4438 locals = rb_thread_local_storage(thread);
4466 if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
4469 locals = rb_thread_local_storage(thread);
4471 return RBOOL(rb_hash_lookup(locals, symbol) !=
Qnil);
4490rb_thread_priority(
VALUE thread)
4492 return INT2NUM(rb_thread_ptr(thread)->priority);
4523rb_thread_priority_set(
VALUE thread,
VALUE prio)
4525 rb_thread_t *target_th = rb_thread_ptr(thread);
4528#if USE_NATIVE_THREAD_PRIORITY
4529 target_th->priority =
NUM2INT(prio);
4530 native_thread_apply_priority(th);
4533 if (priority > RUBY_THREAD_PRIORITY_MAX) {
4534 priority = RUBY_THREAD_PRIORITY_MAX;
4536 else if (priority < RUBY_THREAD_PRIORITY_MIN) {
4537 priority = RUBY_THREAD_PRIORITY_MIN;
4539 target_th->priority = (int8_t)priority;
4541 return INT2NUM(target_th->priority);
4546#if defined(NFDBITS) && defined(HAVE_RB_FD_INIT)
4582 FD_ZERO(fds->
fdset);
4586fdset_memsize(
int maxfd)
4588 size_t o = howmany(maxfd, NFDBITS) *
sizeof(fd_mask);
4589 if (o <
sizeof(fd_set)) {
4590 return sizeof(fd_set);
4598 size_t size = fdset_memsize(
rb_fd_max(src));
4607 ruby_xfree_sized(fds->
fdset, fdset_memsize(fds->
maxfd));
4622 size_t m = fdset_memsize(n + 1);
4623 size_t o = fdset_memsize(fds->
maxfd);
4626 fds->
fdset = ruby_xrealloc_sized(fds->
fdset, m, o);
4627 memset((
char *)fds->
fdset + o, 0, m - o);
4636 FD_SET(n, fds->
fdset);
4642 if (n >= fds->
maxfd)
return;
4643 FD_CLR(n, fds->
fdset);
4649 if (n >= fds->
maxfd)
return 0;
4650 return FD_ISSET(n, fds->
fdset) != 0;
4656 size_t size = fdset_memsize(max);
4657 dst->
fdset = ruby_xrealloc_sized(dst->
fdset, size, fdset_memsize(dst->
maxfd));
4659 memcpy(dst->
fdset, src, size);
4665 size_t size = fdset_memsize(
rb_fd_max(src));
4666 dst->
fdset = ruby_xrealloc_sized(dst->
fdset, size, fdset_memsize(dst->
maxfd));
4674 fd_set *r = NULL, *w = NULL, *e = NULL;
4687 return select(n, r, w, e, timeout);
4690#define rb_fd_no_init(fds) ((void)((fds)->fdset = 0), (void)((fds)->maxfd = 0))
4697#define FD_ZERO(f) rb_fd_zero(f)
4698#define FD_SET(i, f) rb_fd_set((i), (f))
4699#define FD_CLR(i, f) rb_fd_clr((i), (f))
4700#define FD_ISSET(i, f) rb_fd_isset((i), (f))
4702#elif defined(_WIN32)
4707 set->
capa = FD_SETSIZE;
4709 FD_ZERO(set->
fdset);
4720fdset_memsize(
int capa)
4722 return offsetof(fd_set, fd_array) + (
capa *
sizeof(SOCKET));
4728 ruby_xfree_sized(set->
fdset, fdset_memsize(set->
capa));
4737 SOCKET s = rb_w32_get_osfhandle(fd);
4739 for (i = 0; i < set->
fdset->fd_count; i++) {
4740 if (set->
fdset->fd_array[i] == s) {
4744 if (set->
fdset->fd_count >= (
unsigned)set->
capa) {
4745 set->
capa = (set->
fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
4747 rb_xrealloc_mul_add(
4748 set->
fdset, set->
capa,
sizeof(SOCKET), offsetof(fd_set, fd_array));
4750 set->
fdset->fd_array[set->
fdset->fd_count++] = s;
4758#define FD_ZERO(f) rb_fd_zero(f)
4759#define FD_SET(i, f) rb_fd_set((i), (f))
4760#define FD_CLR(i, f) rb_fd_clr((i), (f))
4761#define FD_ISSET(i, f) rb_fd_isset((i), (f))
4763#define rb_fd_no_init(fds) (void)((fds)->fdset = 0)
4767#ifndef rb_fd_no_init
4768#define rb_fd_no_init(fds) (void)(fds)
4772wait_retryable(
volatile int *result,
int errnum, rb_hrtime_t *rel, rb_hrtime_t end)
4782 if (rel && hrtime_update_expire(rel, end)) {
4792 return !hrtime_update_expire(rel, end);
4812select_set_free(
VALUE p)
4827 volatile int result = 0;
4829 rb_hrtime_t *to, rel, end = 0;
4831 timeout_prepare(&to, &rel, &end, set->timeout);
4832 volatile rb_hrtime_t endtime = end;
4833#define restore_fdset(dst, src) \
4834 ((dst) ? rb_fd_dup(dst, src) : (void)0)
4835#define do_select_update() \
4836 (restore_fdset(set->rset, &set->orig_rset), \
4837 restore_fdset(set->wset, &set->orig_wset), \
4838 restore_fdset(set->eset, &set->orig_eset), \
4846 BLOCKING_REGION(set->th, {
4849 if (!RUBY_VM_INTERRUPTED(set->th->ec)) {
4850 result = native_fd_select(set->max,
4851 set->rset, set->wset, set->eset,
4852 rb_hrtime2timeval(&tv, to), set->th);
4853 lerrno = result < 0 ? errno : 0;
4855 }, ubf_select, set->th, TRUE);
4857 RUBY_VM_CHECK_INTS_BLOCKING(set->th->ec);
4858 }
while (wait_retryable(&result, lerrno, to, endtime) && do_select_update());
4860 RUBY_VM_CHECK_INTS_BLOCKING(set->th->ec);
4866 return (
VALUE)result;
4875 set.th = GET_THREAD();
4876 RUBY_VM_CHECK_INTS_BLOCKING(set.th->ec);
4881 set.timeout = timeout;
4883 if (!set.rset && !set.wset && !set.eset) {
4892#define fd_init_copy(f) do { \
4894 rb_fd_resize(set.max - 1, set.f); \
4895 if (&set.orig_##f != set.f) { \
4896 rb_fd_init_copy(&set.orig_##f, set.f); \
4900 rb_fd_no_init(&set.orig_##f); \
4914#define POLLIN_SET (POLLRDNORM | POLLRDBAND | POLLIN | POLLHUP | POLLERR)
4915#define POLLOUT_SET (POLLWRBAND | POLLWRNORM | POLLOUT | POLLERR)
4916#define POLLEX_SET (POLLPRI)
4919# define POLLERR_SET (0)
4923wait_for_single_fd_blocking_region(rb_thread_t *th,
struct pollfd *fds, nfds_t nfds,
4924 rb_hrtime_t *
const to,
volatile int *lerrno)
4928 volatile int result = -1;
4931 BLOCKING_REGION(th, {
4932 if (!RUBY_VM_INTERRUPTED(th->ec)) {
4933 result = ppoll(fds, nfds, rb_hrtime2timespec(&ts, to), 0);
4934 *lerrno = result < 0 ?
errno : 0;
4936 }, ubf_select, th, TRUE);
4944thread_io_wait(rb_thread_t *th,
struct rb_io *io,
int fd,
int events,
struct timeval *timeout)
4946 struct pollfd fds[1] = {{
4948 .events = (short)events,
4951 volatile int result = 0;
4954 enum ruby_tag_type state = TAG_NONE;
4955 volatile int lerrno;
4958 rb_execution_context_t *ec = th->ec;
4961 blocking_operation.ec = ec;
4962 blocking_operation.scheduler_interrupt_target =
Qnil;
4963COMPILER_WARNING_PUSH
4964#if RBIMPL_COMPILER_SINCE(GCC, 12, 0, 0)
4965COMPILER_WARNING_IGNORED(-Wdangling-pointer)
4968 rb_io_blocking_operation_enter(io, &blocking_operation);
4973 struct timeval *
volatile wait_timeout = timeout;
4974 const rb_hrtime_t deadline = timeout ? rb_hrtime_add(rb_hrtime_now(), rb_timeval2hrtime(timeout)) : 0;
4978 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
4979 enum io_wait_result mn_result;
4983 bool mn_wait = wait_timeout == NULL || wait_timeout->tv_sec != 0 || wait_timeout->tv_usec != 0;
4984 mn_result = mn_wait ? thread_io_wait_events(th, fd, events, wait_timeout,
false) : io_wait_unhandled;
4985 if (mn_result == io_wait_ready)
break;
4988 rb_hrtime_t rest = 0;
4990 rb_hrtime_t now = rb_hrtime_now();
4991 rest = now < deadline ? deadline - now : 0;
4992 rb_hrtime2timeval(&tv_rest, &rest);
4993 wait_timeout = &tv_rest;
4995 if (mn_result == io_wait_unhandled)
break;
4996 if (mn_result == io_wait_timed_out && wait_timeout && rest == 0)
break;
5000 RUBY_VM_CHECK_INTS_BLOCKING(ec);
5003 switch (mn_result) {
5005 fds[0].revents = events;
5008 case io_wait_timed_out:
5012 case io_wait_unhandled: {
5013 rb_hrtime_t *to, rel, end = 0;
5014 RUBY_VM_CHECK_INTS_BLOCKING(ec);
5015 timeout_prepare(&to, &rel, &end, wait_timeout);
5017 nfds = numberof(fds);
5018 result = wait_for_single_fd_blocking_region(th, fds, nfds, to, &lerrno);
5020 RUBY_VM_CHECK_INTS_BLOCKING(ec);
5021 }
while (wait_retryable(&result, lerrno, to, end));
5023 RUBY_VM_CHECK_INTS_BLOCKING(ec);
5026 case io_wait_interrupted:
5033 rb_io_blocking_operation_exit(io, &blocking_operation);
5037 EC_JUMP_TAG(ec, state);
5045 if (fds[0].revents & POLLNVAL) {
5055 if (fds[0].revents & POLLIN_SET)
5056 result |= RB_WAITFD_IN;
5057 if (fds[0].revents & POLLOUT_SET)
5058 result |= RB_WAITFD_OUT;
5059 if (fds[0].revents & POLLEX_SET)
5060 result |= RB_WAITFD_PRI;
5063 if (fds[0].revents & POLLERR_SET)
5071 struct rb_io_blocking_operation *blocking_operation;
5084select_single(
VALUE ptr)
5090 args->read, args->write, args->except, args->tv);
5092 args->as.error =
errno;
5095 if (args->read &&
rb_fd_isset(args->as.fd, args->read))
5097 if (args->write &&
rb_fd_isset(args->as.fd, args->write))
5099 if (args->except &&
rb_fd_isset(args->as.fd, args->except))
5106select_single_cleanup(
VALUE ptr)
5110 if (args->blocking_operation) {
5111 rb_io_blocking_operation_exit(args->io, args->blocking_operation);
5134thread_io_wait(rb_thread_t *th,
struct rb_io *io,
int fd,
int events,
struct timeval *timeout)
5143 blocking_operation.ec = th->ec;
5144 blocking_operation.scheduler_interrupt_target =
Qnil;
5145 rb_io_blocking_operation_enter(io, &blocking_operation);
5146 args.blocking_operation = &blocking_operation;
5150 blocking_operation.ec = NULL;
5151 blocking_operation.scheduler_interrupt_target =
Qnil;
5152 args.blocking_operation = NULL;
5156 args.read = (events & RB_WAITFD_IN) ? init_set_fd(fd, &rfds) : NULL;
5157 args.write = (events & RB_WAITFD_OUT) ? init_set_fd(fd, &wfds) : NULL;
5158 args.except = (events & RB_WAITFD_PRI) ? init_set_fd(fd, &efds) : NULL;
5161 int result = (int)
rb_ensure(select_single, ptr, select_single_cleanup, ptr);
5163 errno = args.as.error;
5170rb_thread_wait_for_single_fd(rb_thread_t *th,
int fd,
int events,
struct timeval *timeout)
5172 return thread_io_wait(th, NULL, fd, events, timeout);
5176rb_thread_io_wait(rb_thread_t *th,
struct rb_io *io,
int events,
struct timeval * timeout)
5178 return thread_io_wait(th, io, io->
fd, events, timeout);
5185#ifdef USE_CONSERVATIVE_STACK_END
5187rb_gc_set_stack_end(
VALUE **stack_end_p)
5190COMPILER_WARNING_PUSH
5191#if RBIMPL_COMPILER_SINCE(GCC, 12, 0, 0)
5192COMPILER_WARNING_IGNORED(-Wdangling-pointer);
5194 *stack_end_p = &stack_end;
5204rb_threadptr_check_signal(rb_thread_t *mth)
5207 if (rb_signal_buff_size() > 0) {
5209 threadptr_trap_interrupt(mth);
5214async_bug_fd(
const char *mesg,
int errno_arg,
int fd)
5217 size_t n = strlcpy(buff, mesg,
sizeof(buff));
5218 if (n <
sizeof(buff)-3) {
5221 rb_async_bug_errno(buff, errno_arg);
5226consume_communication_pipe(
int fd)
5232 static char buff[1024];
5238 result = read(fd, buff,
sizeof(buff));
5240 RUBY_DEBUG_LOG(
"resultf:%d buff:%lu", (
int)result, (
unsigned long)buff[0]);
5242 RUBY_DEBUG_LOG(
"result:%d", (
int)result);
5246 if (USE_EVENTFD || result < (ssize_t)
sizeof(buff)) {
5250 else if (result == 0) {
5253 else if (result < 0) {
5259#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
5264 async_bug_fd(
"consume_communication_pipe: read", e, fd);
5271rb_thread_stop_timer_thread(
void)
5273 if (TIMER_THREAD_CREATED_P() && native_stop_timer_thread()) {
5274 native_reset_timer_thread();
5279rb_thread_reset_timer_thread(
void)
5281 native_reset_timer_thread();
5285rb_thread_start_timer_thread(
void)
5288 rb_thread_create_timer_thread();
5292clear_coverage_i(st_data_t key, st_data_t val, st_data_t dummy)
5300 if (GET_VM()->coverage_mode & COVERAGE_TARGET_ONESHOT_LINES) {
5322rb_clear_coverages(
void)
5324 VALUE coverages = rb_get_coverages();
5325 if (
RTEST(coverages)) {
5330#if defined(HAVE_WORKING_FORK)
5333rb_thread_atfork_internal(rb_thread_t *th,
void (*atfork)(rb_thread_t *,
const rb_thread_t *))
5336 rb_vm_t *vm = th->vm;
5337 rb_ractor_t *r = th->ractor;
5338 vm->ractor.main_ractor = r;
5339 vm->ractor.main_thread = th;
5340 r->threads.main = th;
5341 r->status_ = ractor_created;
5343 thread_sched_atfork(TH_SCHED(th));
5348 rb_ractor_t *r_next;
5349 ccan_list_for_each_safe(&vm->ractor.set, r, r_next, vmlr_node) {
5350 if (r != vm->ractor.main_ractor) {
5351 rb_ractor_terminate_atfork(vm, r);
5353 ccan_list_for_each(&r->threads.set, i, lt_node) {
5358 ccan_list_head_init(&vm->ractor.set);
5360 rb_ractor_atfork(vm, th);
5361 rb_vm_postponed_job_atfork();
5368 rb_gc_zombie_objspaces_atfork();
5369 rb_gc_atfork_global_locks();
5370 rb_generic_fields_lock_atfork();
5371 rb_fiber_pool_lock_atfork();
5372 ccan_list_head_init(&th->interrupt_exec_tasks);
5375 rb_ractor_sleeper_threads_clear(th->ractor);
5376 rb_clear_coverages();
5379 rb_thread_reset_timer_thread();
5380 rb_thread_start_timer_thread();
5382 VM_ASSERT(vm->ractor.blocking_cnt == 0);
5383 VM_ASSERT(vm->ractor.cnt == 1);
5387terminate_atfork_i(rb_thread_t *th,
const rb_thread_t *current_th)
5389 if (th != current_th) {
5391 th->scheduler =
Qnil;
5394 rb_mutex_abandon_keeping_mutexes(th);
5395 rb_mutex_abandon_locking_mutex(th);
5396 thread_cleanup_func(th, TRUE);
5400void rb_fiber_atfork(rb_thread_t *);
5404 rb_thread_t *th = GET_THREAD();
5405 rb_threadptr_pending_interrupt_clear(th);
5406 rb_thread_atfork_internal(th, terminate_atfork_i);
5407 th->join_list = NULL;
5408 th->scheduler =
Qnil;
5409 rb_fiber_atfork(th);
5416terminate_atfork_before_exec_i(rb_thread_t *th,
const rb_thread_t *current_th)
5418 if (th != current_th) {
5419 thread_cleanup_func_before_exec(th);
5426 rb_thread_t *th = GET_THREAD();
5427 rb_thread_atfork_internal(th, terminate_atfork_before_exec_i);
5452 0, 0, RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE
5475thgroup_s_alloc(
VALUE klass)
5496thgroup_list(
VALUE group)
5499 rb_thread_t *th = 0;
5500 rb_ractor_t *r = GET_RACTOR();
5502 ccan_list_for_each(&r->threads.set, th, lt_node) {
5503 if (th->thgroup == group) {
5528thgroup_enclose(
VALUE group)
5547thgroup_enclosed_p(
VALUE group)
5552 return RBOOL(data->enclosed);
5585 rb_thread_t *target_th = rb_thread_ptr(thread);
5592 if (data->enclosed) {
5600 if (data->enclosed) {
5602 "can't move from the enclosed thread group");
5605 target_th->thgroup = group;
5613thread_shield_mark(
void *ptr)
5615 rb_gc_mark((
VALUE)ptr);
5620 {thread_shield_mark, 0, 0,},
5621 0, 0, RUBY_TYPED_THREAD_SAFE_FREE
5625thread_shield_alloc(
VALUE klass)
5630#define GetThreadShieldPtr(obj) ((VALUE)rb_check_typeddata((obj), &thread_shield_data_type))
5631#define THREAD_SHIELD_WAITING_MASK (((FL_USER19-1)&~(FL_USER0-1))|FL_USER19)
5632#define THREAD_SHIELD_WAITING_SHIFT (FL_USHIFT)
5633#define THREAD_SHIELD_WAITING_MAX (THREAD_SHIELD_WAITING_MASK>>THREAD_SHIELD_WAITING_SHIFT)
5634STATIC_ASSERT(THREAD_SHIELD_WAITING_MAX, THREAD_SHIELD_WAITING_MAX <= UINT_MAX);
5635static inline unsigned int
5636rb_thread_shield_waiting(
VALUE b)
5638 return ((
RBASIC(b)->flags&THREAD_SHIELD_WAITING_MASK)>>THREAD_SHIELD_WAITING_SHIFT);
5642rb_thread_shield_waiting_inc(
VALUE b)
5644 unsigned int w = rb_thread_shield_waiting(b);
5646 if (w > THREAD_SHIELD_WAITING_MAX)
5648 RBASIC(b)->flags &= ~THREAD_SHIELD_WAITING_MASK;
5649 RBASIC(b)->flags |= ((
VALUE)w << THREAD_SHIELD_WAITING_SHIFT);
5653rb_thread_shield_waiting_dec(
VALUE b)
5655 unsigned int w = rb_thread_shield_waiting(b);
5658 RBASIC(b)->flags &= ~THREAD_SHIELD_WAITING_MASK;
5659 RBASIC(b)->flags |= ((
VALUE)w << THREAD_SHIELD_WAITING_SHIFT);
5663rb_thread_shield_new(
void)
5665 VALUE thread_shield = thread_shield_alloc(rb_cThreadShield);
5667 return thread_shield;
5671rb_thread_shield_owned(
VALUE self)
5673 VALUE mutex = GetThreadShieldPtr(self);
5674 if (!mutex)
return false;
5676 rb_mutex_t *m = mutex_ptr(mutex);
5678 return m->ec_serial == rb_ec_serial(GET_EC());
5690rb_thread_shield_wait(
VALUE self)
5692 VALUE mutex = GetThreadShieldPtr(self);
5695 if (!mutex)
return Qfalse;
5696 m = mutex_ptr(mutex);
5697 if (m->ec_serial == rb_ec_serial(GET_EC()))
return Qnil;
5698 rb_thread_shield_waiting_inc(self);
5700 rb_thread_shield_waiting_dec(self);
5703 return rb_thread_shield_waiting(self) > 0 ?
Qnil :
Qfalse;
5707thread_shield_get_mutex(
VALUE self)
5709 VALUE mutex = GetThreadShieldPtr(self);
5711 rb_raise(
rb_eThreadError,
"destroyed thread shield - %p", (
void *)self);
5719rb_thread_shield_release(
VALUE self)
5721 VALUE mutex = thread_shield_get_mutex(self);
5723 return RBOOL(rb_thread_shield_waiting(self) > 0);
5730rb_thread_shield_destroy(
VALUE self)
5732 VALUE mutex = thread_shield_get_mutex(self);
5735 return RBOOL(rb_thread_shield_waiting(self) > 0);
5739threadptr_recursive_hash(rb_thread_t *th)
5741 return th->ec->local_storage_recursive_hash;
5745threadptr_recursive_hash_set(rb_thread_t *th,
VALUE hash)
5747 th->ec->local_storage_recursive_hash = hash;
5759recursive_list_access(
VALUE sym)
5761 rb_thread_t *th = GET_THREAD();
5762 VALUE hash = threadptr_recursive_hash(th);
5765 hash = rb_ident_hash_new();
5766 threadptr_recursive_hash_set(th, hash);
5770 list = rb_hash_aref(hash, sym);
5773 list = rb_ident_hash_new();
5774 rb_hash_aset(hash, sym, list);
5788#if SIZEOF_LONG == SIZEOF_VOIDP
5789 #define OBJ_ID_EQL(obj_id, other) ((obj_id) == (other))
5790#elif SIZEOF_LONG_LONG == SIZEOF_VOIDP
5791 #define OBJ_ID_EQL(obj_id, other) (RB_BIGNUM_TYPE_P((obj_id)) ? \
5792 rb_big_eql((obj_id), (other)) : ((obj_id) == (other)))
5795 VALUE pair_list = rb_hash_lookup2(list, obj,
Qundef);
5796 if (UNDEF_P(pair_list))
5798 if (paired_obj_id) {
5800 if (!OBJ_ID_EQL(paired_obj_id, pair_list))
5804 if (
NIL_P(rb_hash_lookup(pair_list, paired_obj_id)))
5826 rb_hash_aset(list, obj,
Qtrue);
5828 else if (UNDEF_P(pair_list = rb_hash_lookup2(list, obj,
Qundef))) {
5829 rb_hash_aset(list, obj, paired_obj);
5833 VALUE other_paired_obj = pair_list;
5835 rb_hash_aset(pair_list, other_paired_obj,
Qtrue);
5836 rb_hash_aset(list, obj, pair_list);
5838 rb_hash_aset(pair_list, paired_obj,
Qtrue);
5854 VALUE pair_list = rb_hash_lookup2(list, obj,
Qundef);
5855 if (UNDEF_P(pair_list)) {
5859 rb_hash_delete_entry(pair_list, paired_obj);
5865 rb_hash_delete_entry(list, obj);
5881 return (*p->func)(p->obj, p->arg, FALSE);
5902 p.list = recursive_list_access(sym);
5906 outermost = outer && !recursive_check(p.list,
ID2SYM(recursive_key), 0);
5908 if (recursive_check(p.list, p.obj, pairid)) {
5909 if (outer && !outermost) {
5912 return (*func)(obj, arg, TRUE);
5915 enum ruby_tag_type state;
5920 recursive_push(p.list,
ID2SYM(recursive_key), 0);
5921 recursive_push(p.list, p.obj, p.pairid);
5922 result = rb_catch_protect(p.list, exec_recursive_i, (
VALUE)&p, &state);
5923 if (!recursive_pop(p.list, p.obj, p.pairid))
goto invalid;
5924 if (!recursive_pop(p.list,
ID2SYM(recursive_key), 0))
goto invalid;
5925 if (state != TAG_NONE) EC_JUMP_TAG(GET_EC(), state);
5926 if (result == p.list) {
5927 result = (*func)(obj, arg, TRUE);
5932 recursive_push(p.list, p.obj, p.pairid);
5933 EC_PUSH_TAG(GET_EC());
5934 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
5935 ret = (*func)(obj, arg, FALSE);
5938 if (!recursive_pop(p.list, p.obj, p.pairid)) {
5941 if (state != TAG_NONE) EC_JUMP_TAG(GET_EC(), state);
5950 "for %+"PRIsVALUE
" in %+"PRIsVALUE,
5974 return exec_recursive(func, obj, rb_memory_id(paired_obj), arg, 0,
rb_frame_last_func());
5992 return exec_recursive(func, obj, 0, arg, 1, mid);
6004 return exec_recursive(func, obj, rb_memory_id(paired_obj), arg, 1,
rb_frame_last_func());
6016rb_thread_backtrace_m(
int argc,
VALUE *argv,
VALUE thval)
6018 return rb_vm_thread_backtrace(argc, argv, thval);
6033rb_thread_backtrace_locations_m(
int argc,
VALUE *argv,
VALUE thval)
6035 return rb_vm_thread_backtrace_locations(argc, argv, thval);
6039Init_Thread_Mutex(
void)
6041 rb_thread_t *th = GET_THREAD();
6066 rb_thread_t *th = GET_THREAD();
6129 rb_vm_register_special_exception(ruby_error_stream_closed,
rb_eIOError,
6130 "stream closed in another thread");
6132 cThGroup = rb_define_class(
"ThreadGroup",
rb_cObject);
6139 const char * ptr = getenv(
"RUBY_THREAD_TIMESLICE");
6142 long quantum = strtol(ptr, NULL, 0);
6143 if (quantum > 0 && !(SIZEOF_LONG > 4 && quantum > UINT32_MAX)) {
6144 thread_default_quantum_ms = (uint32_t)quantum;
6147 fprintf(stderr,
"Ignored RUBY_THREAD_TIMESLICE=%s\n", ptr);
6152 th->thgroup = th->ractor->thgroup_default =
rb_obj_alloc(cThGroup);
6153 rb_define_const(cThGroup,
"Default", th->thgroup);
6163#ifdef HAVE_PTHREAD_NP_H
6164 VM_ASSERT(TH_SCHED(th)->running == th);
6171 th->pending_interrupt_queue_checked = 0;
6176 rb_thread_create_timer_thread();
6187 rb_thread_t *th = ruby_thread_from_native();
6192#ifdef NON_SCALAR_THREAD_ID
6193 #define thread_id_str(th) (NULL)
6195 #define thread_id_str(th) ((void *)(uintptr_t)(th)->nt->thread_id)
6199debug_deadlock_check(rb_ractor_t *r,
VALUE msg)
6201 rb_thread_t *th = 0;
6204 rb_str_catf(msg,
"\n%d threads, %d sleeps current:%p main thread:%p\n",
6205 rb_ractor_living_thread_num(r), rb_ractor_sleeper_thread_num(r),
6206 (
void *)GET_THREAD(), (
void *)r->threads.main);
6208 ccan_list_for_each(&r->threads.set, th, lt_node) {
6209 rb_str_catf(msg,
"* %+"PRIsVALUE
"\n rb_thread_t:%p "
6211 th->self, (
void *)th, th->nt ? thread_id_str(th) :
"N/A", th->ec->interrupt_flag);
6213 if (th->locking_mutex) {
6214 rb_mutex_t *mutex = mutex_ptr(th->locking_mutex);
6215 rb_str_catf(msg,
" mutex:%llu cond:%"PRIuSIZE,
6216 (
unsigned long long)mutex->ec_serial, rb_mutex_num_waiting(mutex));
6222 rb_str_catf(msg,
"\n depended by: tb_thread_id:%p", (
void *)list->thread);
6226 rb_str_catf(msg,
"\n ");
6227 rb_str_concat(msg,
rb_ary_join(rb_ec_backtrace_str_ary(th->ec, RUBY_BACKTRACE_START, RUBY_ALL_BACKTRACE_LINES), sep));
6228 rb_str_catf(msg,
"\n");
6233rb_check_deadlock(rb_ractor_t *r)
6235 if (GET_THREAD()->vm->thread_ignore_deadlock)
return;
6237 if (r->threads.sched.readyq_cnt > 0)
return;
6239 int sleeper_num = rb_ractor_sleeper_thread_num(r);
6240 int ltnum = rb_ractor_living_thread_num(r);
6242 if (ltnum > sleeper_num)
return;
6243 if (ltnum < sleeper_num) rb_bug(
"sleeper must not be more than vm_living_thread_num(vm)");
6246 rb_thread_t *th = NULL;
6248 ccan_list_for_each(&r->threads.set, th, lt_node) {
6249 if (th->status != THREAD_STOPPED_FOREVER || RUBY_VM_INTERRUPTED(th->ec)) {
6252 else if (th->locking_mutex) {
6253 rb_mutex_t *mutex = mutex_ptr(th->locking_mutex);
6254 if (mutex->ec_serial == rb_ec_serial(th->ec) || (!mutex->ec_serial && !ccan_list_empty(&mutex->waitq))) {
6265 argv[1] =
rb_str_new2(
"No live threads left. Deadlock?");
6266 debug_deadlock_check(r, argv[1]);
6267 rb_threadptr_raise(r->threads.main, 2, argv);
6274 const rb_control_frame_t *cfp = GET_EC()->cfp;
6275 VALUE coverage = rb_iseq_coverage(CFP_ISEQ(cfp));
6280 VM_ASSERT(line >= 0);
6283 void rb_iseq_clear_event_flags(
const rb_iseq_t *iseq,
size_t start, rb_iseq_events_t reset);
6284 if (GET_VM()->coverage_mode & COVERAGE_TARGET_ONESHOT_LINES) {
6285 rb_iseq_clear_event_flags(CFP_ISEQ(cfp),
FIX2LONG(trace_arg->data), RUBY_EVENT_COVERAGE_LINE);
6305 const rb_control_frame_t *cfp = GET_EC()->cfp;
6306 VALUE coverage = rb_iseq_coverage(CFP_ISEQ(cfp));
6310 long pc = CFP_PC(cfp) - ISEQ_BODY(CFP_ISEQ(cfp))->iseq_encoded - 1;
6322const rb_method_entry_t *
6323rb_resolve_me_location(
const rb_method_entry_t *me,
VALUE resolved_location[5])
6325 VALUE path, beg_pos_lineno, beg_pos_column, end_pos_lineno, end_pos_column;
6326 const rb_method_definition_t *def;
6328 if (!me->def)
return NULL;
6331 def = rb_method_entry_def_acquire(me);
6332 switch (def->type) {
6333 case VM_METHOD_TYPE_ISEQ: {
6334 const rb_iseq_t *iseq = def->body.iseq.
iseqptr;
6335 rb_iseq_location_t *loc = &ISEQ_BODY(iseq)->location;
6336 path = rb_iseq_path(iseq);
6337 beg_pos_lineno =
INT2NUM(loc->code_location.beg_pos.lineno);
6338 beg_pos_column =
INT2NUM(loc->code_location.beg_pos.column);
6339 end_pos_lineno =
INT2NUM(loc->code_location.end_pos.lineno);
6340 end_pos_column =
INT2NUM(loc->code_location.end_pos.column);
6343 case VM_METHOD_TYPE_BMETHOD: {
6344 const rb_iseq_t *iseq = rb_proc_get_iseq(def->body.bmethod.proc, 0);
6346 rb_iseq_location_t *loc;
6347 rb_iseq_check(iseq);
6348 path = rb_iseq_path(iseq);
6349 loc = &ISEQ_BODY(iseq)->location;
6350 beg_pos_lineno =
INT2NUM(loc->code_location.beg_pos.lineno);
6351 beg_pos_column =
INT2NUM(loc->code_location.beg_pos.column);
6352 end_pos_lineno =
INT2NUM(loc->code_location.end_pos.lineno);
6353 end_pos_column =
INT2NUM(loc->code_location.end_pos.column);
6358 case VM_METHOD_TYPE_ALIAS:
6359 me = rb_method_alias_original_me(def);
6361 case VM_METHOD_TYPE_REFINED:
6362 me = def->body.refined.orig_me;
6363 if (!me)
return NULL;
6374 if (resolved_location) {
6375 resolved_location[0] = path;
6376 resolved_location[1] = beg_pos_lineno;
6377 resolved_location[2] = beg_pos_column;
6378 resolved_location[3] = end_pos_lineno;
6379 resolved_location[4] = end_pos_column;
6385 rb_coverage_method_callback *callback;
6395 const rb_method_entry_t *me = (
const rb_method_entry_t *)me_v;
6397 const rb_method_entry_t *resolved_me = rb_resolve_me_location(me, location);
6400 FIX2LONG(location[1]) <= 0)
return false;
6402 out->owner = me->owner;
6403 out->method_id =
ID2SYM(me->def->original_id);
6404 out->path = location[0];
6405 out->first_lineno = location[1];
6406 out->first_column = location[2];
6407 out->last_lineno = location[3];
6408 out->last_column = location[4];
6414method_coverage_call(
const rb_method_entry_t *me,
VALUE count,
6418 if (rb_coverage_method_data_of((
VALUE)me, count, &method)) {
6419 arg->callback(&method, arg->data);
6426 method_coverage_call((
const rb_method_entry_t *)me,
INT2FIX(0),
6435 method_coverage_call((
const rb_method_entry_t *)me, count,
6441rb_coverage_each_method(rb_coverage_method_callback callback,
void *data)
6444 VALUE me_set = GET_VM()->me_set;
6445 VALUE cme2counter = GET_VM()->cme2counter;
6447 if (
RTEST(me_set)) {
6450 if (
RTEST(cme2counter)) {
6458 const rb_control_frame_t *cfp = GET_EC()->cfp;
6459 const rb_callable_method_entry_t *cme = rb_vm_frame_method_entry(cfp);
6460 const rb_method_entry_t *me = (
const rb_method_entry_t *)cme;
6464 me = rb_resolve_me_location(me, 0);
6467 rcount = rb_hash_aref(cme2counter, (
VALUE) me);
6482rb_vm_coverage_record_me(
const rb_method_entry_t *me)
6484 if (!
RTEST(GET_VM()->coverages))
return;
6485 if (!(GET_VM()->coverage_mode & COVERAGE_TARGET_METHODS))
return;
6487 VALUE me_set = GET_VM()->me_set;
6488 if (!
RTEST(me_set))
return;
6490 if (rb_resolve_me_location(me, 0) == me) {
6496rb_get_coverages(
void)
6498 return GET_VM()->coverages;
6502rb_get_coverage_mode(
void)
6504 return GET_VM()->coverage_mode;
6508rb_set_coverages(
VALUE coverages,
int mode,
VALUE cme2counter,
VALUE me_set)
6510 GET_VM()->coverages = coverages;
6511 GET_VM()->cme2counter = cme2counter;
6512 GET_VM()->me_set = me_set;
6513 GET_VM()->coverage_mode = mode;
6517rb_resume_coverages(
void)
6519 int mode = GET_VM()->coverage_mode;
6520 VALUE cme2counter = GET_VM()->cme2counter;
6521 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);
6522 if (mode & COVERAGE_TARGET_BRANCHES) {
6523 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);
6525 if (mode & COVERAGE_TARGET_METHODS) {
6531rb_suspend_coverages(
void)
6534 if (GET_VM()->coverage_mode & COVERAGE_TARGET_BRANCHES) {
6537 if (GET_VM()->coverage_mode & COVERAGE_TARGET_METHODS) {
6544rb_reset_coverages(
void)
6546 rb_clear_coverages();
6547 rb_iseq_remove_coverage_all();
6548 GET_VM()->coverages =
Qfalse;
6549 GET_VM()->cme2counter =
Qnil;
6550 GET_VM()->me_set =
Qnil;
6554rb_default_coverage(
int n)
6556 VALUE coverage = rb_ary_hidden_new_fill(3);
6558 int mode = GET_VM()->coverage_mode;
6560 if (mode & COVERAGE_TARGET_LINES) {
6563 RARRAY_ASET(coverage, COVERAGE_INDEX_LINES, lines);
6565 if (mode & COVERAGE_TARGET_BRANCHES) {
6566 branches = rb_ary_hidden_new_fill(2);
6594 RARRAY_ASET(coverage, COVERAGE_INDEX_BRANCHES, branches);
6600uninterruptible_exit(
VALUE v)
6602 rb_thread_t *cur_th = GET_THREAD();
6603 rb_ary_pop(cur_th->pending_interrupt_mask_stack);
6605 cur_th->pending_interrupt_queue_checked = 0;
6606 if (!rb_threadptr_pending_interrupt_empty_p(cur_th)) {
6607 RUBY_VM_SET_INTERRUPT(cur_th->ec);
6615 VALUE interrupt_mask = rb_ident_hash_new();
6616 rb_thread_t *cur_th = GET_THREAD();
6618 rb_hash_aset(interrupt_mask,
rb_cObject, sym_never);
6620 rb_ary_push(cur_th->pending_interrupt_mask_stack, interrupt_mask);
6624 RUBY_VM_CHECK_INTS(cur_th->ec);
6629thread_specific_storage_alloc(rb_thread_t *th)
6631 VM_ASSERT(th->specific_storage == NULL);
6633 if (UNLIKELY(specific_key_count > 0)) {
6634 th->specific_storage =
ZALLOC_N(
void *, RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX);
6638rb_internal_thread_specific_key_t
6641 rb_vm_t *vm = GET_VM();
6643 if (specific_key_count == 0 && vm->ractor.cnt > 1) {
6644 rb_raise(
rb_eThreadError,
"The first rb_internal_thread_specific_key_create() is called with multiple ractors");
6646 else if (specific_key_count >= RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX) {
6647 rb_raise(
rb_eThreadError,
"rb_internal_thread_specific_key_create() is called more than %d times", RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX);
6650 rb_internal_thread_specific_key_t key = specific_key_count++;
6654 rb_ractor_t *cr = GET_RACTOR();
6657 ccan_list_for_each(&cr->threads.set, th, lt_node) {
6658 thread_specific_storage_alloc(th);
6669 rb_thread_t *th =
DATA_PTR(thread_val);
6671 VM_ASSERT(rb_thread_ptr(thread_val) == th);
6672 VM_ASSERT(key < RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX);
6673 VM_ASSERT(th->specific_storage);
6675 return th->specific_storage[key];
6682 rb_thread_t *th =
DATA_PTR(thread_val);
6684 VM_ASSERT(rb_thread_ptr(thread_val) == th);
6685 VM_ASSERT(key < RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX);
6686 VM_ASSERT(th->specific_storage);
6688 th->specific_storage[key] = data;
6694 struct ccan_list_node node;
6696 rb_interrupt_exec_func_t *func;
6698 enum rb_interrupt_exec_flag flags;
6702rb_threadptr_interrupt_exec_task_mark(rb_thread_t *th)
6706 ccan_list_for_each(&th->interrupt_exec_tasks, task, node) {
6707 if (task->flags & rb_interrupt_exec_flag_value_data) {
6708 rb_gc_mark((
VALUE)task->data);
6716rb_threadptr_interrupt_exec(rb_thread_t *th, rb_interrupt_exec_func_t *func,
void *data,
enum rb_interrupt_exec_flag flags)
6728 ccan_list_add_tail(&th->interrupt_exec_tasks, &task->node);
6729 threadptr_set_interrupt_locked(th,
true);
6735threadptr_interrupt_exec_exec(rb_thread_t *th)
6746 RUBY_DEBUG_LOG(
"task:%p", task);
6749 if (task->flags & rb_interrupt_exec_flag_new_thread) {
6753 (*task->func)(task->data);
6764threadptr_interrupt_exec_cleanup(rb_thread_t *th)
6781 rb_interrupt_exec_func_t *func,
void *data,
enum rb_interrupt_exec_flag flags)
6783 RUBY_DEBUG_LOG(
"flags:%d", (
int)flags);
6785 rb_thread_t *main_th = target_r->threads.main;
6786 rb_threadptr_interrupt_exec(main_th, func, data, flags | rb_interrupt_exec_flag_new_thread);
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.
struct rb_trace_arg_struct rb_trace_arg_t
Type that represents a specific trace event.
#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.
#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().
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 Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
#define OBJ_FROZEN
Old name of RB_OBJ_FROZEN.
#define UNREACHABLE
Old name of RBIMPL_UNREACHABLE.
#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 LONG2NUM
Old name of RB_LONG2NUM.
#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_eInterrupt
Interrupt 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_eException
Mother of all exceptions.
VALUE rb_exc_new(VALUE etype, const char *ptr, rb_len_t len)
Creates an instance of the passed exception class.
VALUE rb_eThreadError
ThreadError exception.
void rb_exit(int status)
Terminates the current execution context.
VALUE rb_eSignal
SignalException exception.
VALUE rb_cObject
Object class.
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.
#define RUBY_ASSERT_ALWAYS(expr,...)
A variant of RUBY_ASSERT that does not interface with RUBY_DEBUG.
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
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_fiber_interrupt(VALUE scheduler, VALUE target, VALUE exception)
Interrupt a target by raising an exception.
VALUE rb_fiber_scheduler_yield(VALUE scheduler)
Yield to the scheduler, to be resumed on the next scheduling cycle.
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_current_for_threadptr(struct rb_thread_struct *thread)
Identical to rb_fiber_scheduler_current_for_thread(), except it expects a threadptr instead of a thre...
VALUE rb_fiber_scheduler_unblock(VALUE scheduler, VALUE blocker, VALUE fiber)
Wakes up a fiber previously blocked using rb_fiber_scheduler_block().
VALUE rb_ary_shift(VALUE ary)
Destructively deletes an element from the beginning of the passed array and returns what was deleted.
VALUE rb_ary_entry(VALUE ary, rb_len_t off)
Queries an element of an array.
VALUE rb_ary_dup(VALUE ary)
Duplicates an array.
VALUE rb_ary_delete_at(VALUE ary, rb_len_t pos)
Destructively removes an element which resides at the specific index of the passed array.
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_pop(VALUE ary)
Destructively deletes an element from the end of the passed array and returns what was deleted.
VALUE rb_ary_clear(VALUE ary)
Destructively removes everything form an array.
VALUE rb_ary_hidden_new(rb_len_t capa)
Allocates a hidden (no class) empty array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_ary_join(VALUE ary, VALUE sep)
Recursively stringises the elements of the passed array, flattens that result, then joins the sequenc...
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
VALUE rb_hash_new(void)
Creates a new, empty hash object.
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)
This function is now a no-op.
void rb_thread_wait_for(struct timeval time)
Identical to rb_thread_sleep(), except it takes struct timeval instead.
VALUE rb_mutex_synchronize(VALUE mutex, VALUE(*func)(VALUE arg), VALUE arg)
Obtains the lock, runs the passed function, and releases the lock when it completes.
VALUE rb_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.
ID rb_to_id(VALUE str)
Identical to rb_intern_str(), except it tries to convert the parameter object to an instance of rb_cS...
int capa
Designed capacity of the buffer.
#define RB_IO_POINTER(obj, fp)
Queries the underlying IO pointer.
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.
int ruby_thread_has_gvl_p(void)
Whether the current thread is holding the GVL.
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 processing interrupts after the given function retur...
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.
#define RB_NOGVL_PENDING_INTR_FAIL
Passing this flag to rb_nogvl() prevents it from entering the blocking region if the current thread h...
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.
fd_set rb_fdset_t
The data structure which wraps the fd_set bitmap used by select(2).
#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.
#define RARRAY_AREF(a, i)
References an object in an array.
static void RARRAY_ASET(VALUE ary, rb_len_t i, VALUE v)
Assigns an object in an array.
#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 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 DATA_PTR(obj)
Convenient casting macro for backward compatibility.
#define TypedData_Wrap_Struct(klass, data_type, sval)
Converts sval, a pointer to your struct, into a Ruby object.
struct rb_data_type_struct rb_data_type_t
This is the struct that holds necessary info for a 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...
int rb_errno(void)
Identical to system errno.
#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.
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.
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.
VALUE self
The IO's Ruby level counterpart.
struct ccan_list_head blocking_operations
Threads that are performing a blocking operation without the GVL using this IO.
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_cond_initialize(rb_nativethread_cond_t *cond)
Fills the passed condition variable with an initial value.
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.
long rb_len_t
A signed integer type for lengths and indices of objects such as String and Array.
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.