61#undef __USE_FORTIFY_LEVEL
62#define __USE_FORTIFY_LEVEL 0
66#include "ruby/internal/config.h"
73#define TH_SCHED(th) (&(th)->ractor->threads.sched)
75#include "eval_intern.h"
78#include "internal/class.h"
79#include "internal/cont.h"
80#include "internal/error.h"
81#include "internal/eval.h"
82#include "internal/gc.h"
83#include "internal/hash.h"
84#include "internal/io.h"
85#include "internal/object.h"
86#include "internal/proc.h"
88#include "internal/signal.h"
89#include "internal/thread.h"
90#include "internal/time.h"
91#include "internal/warnings.h"
99#include "ractor_core.h"
103#include "ccan/list/list.h"
105#ifndef USE_NATIVE_THREAD_PRIORITY
106#define USE_NATIVE_THREAD_PRIORITY 0
107#define RUBY_THREAD_PRIORITY_MAX 3
108#define RUBY_THREAD_PRIORITY_MIN -3
111static VALUE rb_cThreadShield;
112static VALUE cThGroup;
114static VALUE sym_immediate;
115static VALUE sym_on_blocking;
116static VALUE sym_never;
118static uint32_t thread_default_quantum_ms = 100;
120#define THREAD_LOCAL_STORAGE_INITIALISED FL_USER13
121#define THREAD_LOCAL_STORAGE_INITIALISED_P(th) RB_FL_TEST_RAW((th), THREAD_LOCAL_STORAGE_INITIALISED)
124rb_thread_local_storage(
VALUE thread)
126 if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
134 SLEEP_DEADLOCKABLE = 0x01,
135 SLEEP_SPURIOUS_CHECK = 0x02,
136 SLEEP_ALLOW_SPURIOUS = 0x04,
137 SLEEP_NO_CHECKINTS = 0x08,
140static void sleep_forever(
rb_thread_t *th,
unsigned int fl);
141static int sleep_hrtime(
rb_thread_t *, rb_hrtime_t,
unsigned int fl);
143static void rb_thread_sleep_deadly_allow_spurious_wakeup(
VALUE blocker,
VALUE timeout, rb_hrtime_t end);
146static int rb_threadptr_pending_interrupt_empty_p(
const rb_thread_t *th);
147static const char *thread_status_name(
rb_thread_t *th,
int detail);
148static int hrtime_update_expire(rb_hrtime_t *,
const rb_hrtime_t);
149NORETURN(
static void async_bug_fd(
const char *mesg,
int errno_arg,
int fd));
150MAYBE_UNUSED(
static int consume_communication_pipe(
int fd));
153static rb_internal_thread_specific_key_t specific_key_count;
157#define THREAD_SYSTEM_DEPENDENT_IMPLEMENTATION
160 enum rb_thread_status prev_status;
164static void unblock_function_clear(
rb_thread_t *th);
170#define THREAD_BLOCKING_BEGIN(th) do { \
171 struct rb_thread_sched * const sched = TH_SCHED(th); \
172 RB_VM_SAVE_MACHINE_CONTEXT(th); \
173 thread_sched_to_waiting((sched), (th));
175#define THREAD_BLOCKING_END(th) \
176 thread_sched_to_running((sched), (th)); \
177 rb_ractor_thread_switch(th->ractor, th, false); \
181#ifdef HAVE_BUILTIN___BUILTIN_CHOOSE_EXPR_CONSTANT_P
182#define only_if_constant(expr, notconst) __builtin_choose_expr(__builtin_constant_p(expr), (expr), (notconst))
184#define only_if_constant(expr, notconst) (__builtin_constant_p(expr) ? (expr) : (notconst))
187#define only_if_constant(expr, notconst) notconst
189#define BLOCKING_REGION(th, exec, ubf, ubfarg, fail_if_interrupted) do { \
190 struct rb_blocking_region_buffer __region; \
191 if (blocking_region_begin(th, &__region, (ubf), (ubfarg), fail_if_interrupted) || \
193 !only_if_constant(fail_if_interrupted, TRUE)) { \
196 RB_VM_SAVE_MACHINE_CONTEXT(th); \
197 thread_sched_to_waiting(TH_SCHED(th), th); \
199 blocking_region_end(th, &__region); \
207#define RUBY_VM_CHECK_INTS_BLOCKING(ec) vm_check_ints_blocking(ec)
211#ifdef RUBY_ASSERT_CRITICAL_SECTION
212 VM_ASSERT(ruby_assert_critical_section_entered == 0);
217 if (LIKELY(rb_threadptr_pending_interrupt_empty_p(th))) {
218 if (LIKELY(!RUBY_VM_INTERRUPTED_ANY(ec)))
return FALSE;
221 th->pending_interrupt_queue_checked = 0;
222 RUBY_VM_SET_INTERRUPT(ec);
224 return rb_threadptr_execute_interrupts(th, 1);
230 return vm_check_ints_blocking(ec);
238#if defined(HAVE_POLL)
239# if defined(__linux__)
242# if defined(__FreeBSD_version) && __FreeBSD_version >= 1100000
245# define POLLERR_SET (POLLHUP | POLLERR)
250timeout_prepare(rb_hrtime_t **to, rb_hrtime_t *rel, rb_hrtime_t *end,
254 *rel = rb_timeval2hrtime(timeout);
255 *end = rb_hrtime_add(rb_hrtime_now(), *rel);
263MAYBE_UNUSED(NOINLINE(
static int thread_start_func_2(
rb_thread_t *th,
VALUE *stack_start)));
264MAYBE_UNUSED(
static bool th_has_dedicated_nt(
const rb_thread_t *th));
265MAYBE_UNUSED(
static int waitfd_to_waiting_flag(
int wfd_event));
267#include THREAD_IMPL_SRC
274#ifndef BUSY_WAIT_SIGNALS
275# define BUSY_WAIT_SIGNALS (0)
279# define USE_EVENTFD (0)
282#include "thread_sync.c"
312 if (fail_if_interrupted) {
313 if (RUBY_VM_INTERRUPTED_ANY(th->ec)) {
318 RUBY_VM_CHECK_INTS(th->ec);
322 }
while (!th->ec->raised_flag && RUBY_VM_INTERRUPTED_ANY(th->ec) &&
325 VM_ASSERT(th->unblock.func == NULL);
327 th->unblock.func = func;
328 th->unblock.arg = arg;
338 th->unblock.func = 0;
343threadptr_set_interrupt_locked(
rb_thread_t *th,
bool trap)
347 RUBY_DEBUG_LOG(
"th:%u trap:%d", rb_th_serial(th), trap);
350 RUBY_VM_SET_TRAP_INTERRUPT(th->ec);
353 RUBY_VM_SET_INTERRUPT(th->ec);
356 if (th->unblock.func != NULL) {
357 (th->unblock.func)(th->unblock.arg);
369 threadptr_set_interrupt_locked(th, trap);
378 RUBY_DEBUG_LOG(
"th:%u", rb_th_serial(th));
379 threadptr_set_interrupt(th,
false);
385 threadptr_set_interrupt(th,
true);
393 ccan_list_for_each(&r->threads.set, th, lt_node) {
394 if (th != main_thread) {
395 RUBY_DEBUG_LOG(
"terminate start th:%u status:%s", rb_th_serial(th), thread_status_name(th, TRUE));
397 rb_threadptr_pending_interrupt_enque(th, RUBY_FATAL_THREAD_TERMINATED);
398 rb_threadptr_interrupt(th);
400 RUBY_DEBUG_LOG(
"terminate done th:%u status:%s", rb_th_serial(th), thread_status_name(th, TRUE));
403 RUBY_DEBUG_LOG(
"main thread th:%u", rb_th_serial(th));
411 while (thread->join_list) {
415 thread->join_list = join_list->next;
419 if (target_thread->scheduler !=
Qnil && join_list->fiber) {
423 rb_threadptr_interrupt(target_thread);
425 switch (target_thread->status) {
427 case THREAD_STOPPED_FOREVER:
428 target_thread->status = THREAD_RUNNABLE;
438rb_threadptr_unlock_all_locking_mutexes(
rb_thread_t *th)
440 while (th->keeping_mutexes) {
442 th->keeping_mutexes = mutex->next_mutex;
445 VM_ASSERT(mutex->fiber_serial);
446 const char *error_message = rb_mutex_unlock_th(mutex, th, NULL);
447 if (error_message) rb_bug(
"invalid keeping_mutexes: %s", error_message);
456 volatile int sleeping = 0;
458 if (cr->threads.main != th) {
459 rb_bug(
"rb_thread_terminate_all: called by child thread (%p, %p)",
460 (
void *)cr->threads.main, (
void *)th);
464 rb_threadptr_unlock_all_locking_mutexes(th);
467 if (EC_EXEC_TAG() == TAG_NONE) {
469 RUBY_DEBUG_LOG(
"th:%u", rb_th_serial(th));
471 terminate_all(cr, th);
473 while (rb_ractor_living_thread_num(cr) > 1) {
474 rb_hrtime_t rel = RB_HRTIME_PER_SEC;
480 native_sleep(th, &rel);
481 RUBY_VM_CHECK_INTS_BLOCKING(ec);
499void rb_threadptr_root_fiber_terminate(
rb_thread_t *th);
500static void threadptr_interrupt_exec_cleanup(
rb_thread_t *th);
503thread_cleanup_func_before_exec(
void *th_ptr)
506 th->status = THREAD_KILLED;
509 th->ec->machine.stack_start = th->ec->machine.stack_end = NULL;
511 threadptr_interrupt_exec_cleanup(th);
512 rb_threadptr_root_fiber_terminate(th);
516thread_cleanup_func(
void *th_ptr,
int atfork)
520 th->locking_mutex =
Qfalse;
521 thread_cleanup_func_before_exec(th_ptr);
524 native_thread_destroy_atfork(th->nt);
533rb_thread_free_native_thread(
void *th_ptr)
537 native_thread_destroy_atfork(th->nt);
545ruby_thread_init_stack(
rb_thread_t *th,
void *local_in_parent_frame)
547 native_thread_init_stack(th, local_in_parent_frame);
551rb_vm_proc_local_ep(
VALUE proc)
553 const VALUE *ep = vm_proc_ep(proc);
556 return rb_vm_ep_local_ep(ep);
565 int argc,
const VALUE *argv,
int kw_splat,
VALUE passed_block_handler);
570 VALUE args = th->invoke_arg.proc.args;
571 const VALUE *args_ptr;
573 VALUE procval = th->invoke_arg.proc.proc;
575 GetProcPtr(procval, proc);
577 th->ec->errinfo =
Qnil;
578 th->ec->root_lep = rb_vm_proc_local_ep(procval);
579 th->ec->root_svar =
Qfalse;
581 vm_check_ints_blocking(th->ec);
583 if (th->invoke_type == thread_invoke_type_ractor_proc) {
584 VALUE self = rb_ractor_self(th->ractor);
585 th->thgroup = th->ractor->thgroup_default =
rb_obj_alloc(cThGroup);
590 rb_ractor_receive_parameters(th->ec, th->ractor, args_len, (
VALUE *)args_ptr);
591 vm_check_ints_blocking(th->ec);
593 return rb_vm_invoke_proc_with_self(
596 th->invoke_arg.proc.kw_splat,
597 VM_BLOCK_HANDLER_NONE
606 th->invoke_arg.proc.args =
Qnil;
612 vm_check_ints_blocking(th->ec);
614 return rb_vm_invoke_proc(
617 th->invoke_arg.proc.kw_splat,
618 VM_BLOCK_HANDLER_NONE
626 native_set_thread_name(th);
629 switch (th->invoke_type) {
630 case thread_invoke_type_proc:
631 result = thread_do_start_proc(th);
634 case thread_invoke_type_ractor_proc:
635 result = thread_do_start_proc(th);
636 rb_ractor_atexit(th->ec, result);
639 case thread_invoke_type_func:
640 result = (*th->invoke_arg.func.func)(th->invoke_arg.func.arg);
643 case thread_invoke_type_none:
644 rb_bug(
"unreachable");
655 RUBY_DEBUG_LOG(
"th:%u", rb_th_serial(th));
656 VM_ASSERT(th != th->vm->ractor.main_thread);
658 enum ruby_tag_type state;
660 rb_thread_t *ractor_main_th = th->ractor->threads.main;
663 if (rb_ractor_status_p(th->ractor, ractor_blocking)) {
666 rb_vm_ractor_blocking_cnt_dec(th->vm, th->ractor, __FILE__, __LINE__);
668 r->r_stdin = rb_io_prep_stdin();
669 r->r_stdout = rb_io_prep_stdout();
670 r->r_stderr = rb_io_prep_stderr();
676 VM_ASSERT(UNDEF_P(th->value));
678 int fiber_scheduler_closed = 0, event_thread_end_hooked = 0;
683 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
686 result = thread_do_start(th);
689 if (!fiber_scheduler_closed) {
690 fiber_scheduler_closed = 1;
694 if (!event_thread_end_hooked) {
695 event_thread_end_hooked = 1;
699 if (state == TAG_NONE) {
704 errinfo = th->ec->errinfo;
706 VALUE exc = rb_vm_make_jump_tag_but_local_jump(state,
Qundef);
707 if (!
NIL_P(exc)) errinfo = exc;
709 if (state == TAG_FATAL) {
710 if (th->invoke_type == thread_invoke_type_ractor_proc) {
711 rb_ractor_atexit(th->ec,
Qnil);
716 if (th->invoke_type == thread_invoke_type_ractor_proc) {
717 rb_ractor_atexit_exception(th->ec);
723 if (th->report_on_exception) {
724 VALUE mesg = rb_thread_to_s(th->self);
725 rb_str_cat_cstr(mesg,
" terminated with exception (report_on_exception is true):\n");
726 rb_write_error_str(mesg);
727 rb_ec_error_print(th->ec, errinfo);
730 if (th->invoke_type == thread_invoke_type_ractor_proc) {
731 rb_ractor_atexit_exception(th->ec);
734 if (th->vm->thread_abort_on_exception ||
746 VM_ASSERT(!UNDEF_P(th->value));
748 rb_threadptr_join_list_wakeup(th);
749 rb_threadptr_unlock_all_locking_mutexes(th);
751 if (th->invoke_type == thread_invoke_type_ractor_proc) {
752 rb_thread_terminate_all(th);
753 rb_ractor_teardown(th->ec);
756 th->status = THREAD_KILLED;
757 RUBY_DEBUG_LOG(
"killed th:%u", rb_th_serial(th));
759 if (th->vm->ractor.main_thread == th) {
765 rb_threadptr_raise(ractor_main_th, 1, &errinfo);
770 rb_ec_clear_current_thread_trace_func(th->ec);
773 if (th->locking_mutex !=
Qfalse) {
774 rb_bug(
"thread_start_func_2: locking_mutex must not be set (%p:%"PRIxVALUE
")",
775 (
void *)th, th->locking_mutex);
778 if (ractor_main_th->status == THREAD_KILLED &&
779 th->ractor->threads.cnt <= 2 ) {
781 rb_threadptr_interrupt(ractor_main_th);
784 rb_check_deadlock(th->ractor);
786 rb_fiber_close(th->ec->fiber_ptr);
788 thread_cleanup_func(th, FALSE);
789 VM_ASSERT(th->ec->vm_stack == NULL);
791 if (th->invoke_type == thread_invoke_type_ractor_proc) {
795 thread_sched_to_dead(TH_SCHED(th), th);
796 rb_ractor_living_threads_remove(th->ractor, th);
799 rb_ractor_living_threads_remove(th->ractor, th);
800 thread_sched_to_dead(TH_SCHED(th), th);
807 enum thread_invoke_type type;
820static void thread_specific_storage_alloc(
rb_thread_t *th);
826 rb_thread_t *th = rb_thread_ptr(thval), *current_th = rb_ec_thread_ptr(ec);
829 thread_specific_storage_alloc(th);
833 "can't start a new thread (frozen ThreadGroup)");
836 rb_fiber_inherit_storage(ec, th->ec->fiber_ptr);
838 switch (params->type) {
839 case thread_invoke_type_proc:
840 th->invoke_type = thread_invoke_type_proc;
841 th->invoke_arg.proc.args = params->args;
842 th->invoke_arg.proc.proc = params->proc;
846 case thread_invoke_type_ractor_proc:
847#if RACTOR_CHECK_MODE > 0
848 rb_ractor_setup_belonging_to(thval, rb_ractor_id(params->g));
850 th->invoke_type = thread_invoke_type_ractor_proc;
851 th->ractor = params->g;
852 th->ractor->threads.main = th;
853 th->invoke_arg.proc.proc = rb_proc_isolate_bang(params->proc,
Qnil);
856 rb_ractor_send_parameters(ec, params->g, params->args);
859 case thread_invoke_type_func:
860 th->invoke_type = thread_invoke_type_func;
861 th->invoke_arg.func.func = params->fn;
862 th->invoke_arg.func.arg = (
void *)params->args;
866 rb_bug(
"unreachable");
869 th->priority = current_th->priority;
870 th->thgroup = current_th->thgroup;
873 th->pending_interrupt_queue_checked = 0;
874 th->pending_interrupt_mask_stack =
rb_ary_dup(current_th->pending_interrupt_mask_stack);
875 RBASIC_CLEAR_CLASS(th->pending_interrupt_mask_stack);
879 RUBY_DEBUG_LOG(
"r:%u th:%u", rb_ractor_id(th->ractor), rb_th_serial(th));
881 rb_ractor_living_threads_insert(th->ractor, th);
884 err = native_thread_create(th);
886 th->status = THREAD_KILLED;
887 rb_ractor_living_threads_remove(th->ractor, th);
893#define threadptr_initialized(th) ((th)->invoke_type != thread_invoke_type_none)
916thread_s_new(
int argc,
VALUE *argv,
VALUE klass)
919 VALUE thread = rb_thread_alloc(klass);
921 if (GET_RACTOR()->threads.main->status == THREAD_KILLED) {
926 th = rb_thread_ptr(thread);
927 if (!threadptr_initialized(th)) {
928 rb_raise(
rb_eThreadError,
"uninitialized thread - check '%"PRIsVALUE
"#initialize'",
948 .type = thread_invoke_type_proc,
952 return thread_create_core(rb_thread_alloc(klass), ¶ms);
958 if (th->invoke_type == thread_invoke_type_proc) {
959 return rb_proc_location(th->invoke_arg.proc.proc);
975 else if (th->invoke_type != thread_invoke_type_none) {
976 VALUE loc = threadptr_invoke_proc_location(th);
979 "already initialized thread - %"PRIsVALUE
":%"PRIsVALUE,
988 .type = thread_invoke_type_proc,
992 return thread_create_core(thread, ¶ms);
1000 .type = thread_invoke_type_func,
1004 return thread_create_core(rb_thread_alloc(
rb_cThread), ¶ms);
1011 .type = thread_invoke_type_ractor_proc,
1016 return thread_create_core(rb_thread_alloc(
rb_cThread), ¶ms);
1028remove_from_join_list(
VALUE arg)
1033 if (target_thread->status != THREAD_KILLED) {
1036 while (*join_list) {
1037 if (*join_list == p->waiter) {
1038 *join_list = (*join_list)->next;
1042 join_list = &(*join_list)->next;
1052 return th->status == THREAD_KILLED || !UNDEF_P(th->value);
1056thread_join_sleep(
VALUE arg)
1059 rb_thread_t *target_th = p->target, *th = p->waiter->thread;
1060 rb_hrtime_t end = 0, *limit = p->limit;
1063 end = rb_hrtime_add(*limit, rb_hrtime_now());
1066 while (!thread_finished(target_th)) {
1070 if (scheduler !=
Qnil) {
1074 sleep_forever(th, SLEEP_DEADLOCKABLE | SLEEP_ALLOW_SPURIOUS | SLEEP_NO_CHECKINTS);
1078 if (hrtime_update_expire(limit, end)) {
1079 RUBY_DEBUG_LOG(
"timeout target_th:%u", rb_th_serial(target_th));
1083 if (scheduler !=
Qnil) {
1084 VALUE timeout = rb_float_new(hrtime2double(*limit));
1088 th->status = THREAD_STOPPED;
1089 native_sleep(th, limit);
1092 RUBY_VM_CHECK_INTS_BLOCKING(th->ec);
1093 th->status = THREAD_RUNNABLE;
1095 RUBY_DEBUG_LOG(
"interrupted target_th:%u status:%s", rb_th_serial(target_th), thread_status_name(target_th, TRUE));
1108 if (th == target_th) {
1109 rb_raise(
rb_eThreadError,
"Target thread must not be current thread");
1112 if (th->ractor->threads.main == target_th) {
1116 RUBY_DEBUG_LOG(
"target_th:%u status:%s", rb_th_serial(target_th), thread_status_name(target_th, TRUE));
1118 if (target_th->status != THREAD_KILLED) {
1120 waiter.next = target_th->join_list;
1122 waiter.fiber = rb_fiberptr_blocking(fiber) ? NULL : fiber;
1123 target_th->join_list = &waiter;
1126 arg.waiter = &waiter;
1127 arg.target = target_th;
1128 arg.timeout = timeout;
1136 RUBY_DEBUG_LOG(
"success target_th:%u status:%s", rb_th_serial(target_th), thread_status_name(target_th, TRUE));
1138 if (target_th->ec->errinfo !=
Qnil) {
1139 VALUE err = target_th->ec->errinfo;
1144 RUBY_DEBUG_LOG(
"terminated target_th:%u status:%s", rb_th_serial(target_th), thread_status_name(target_th, TRUE));
1149 if (err == RUBY_FATAL_FIBER_KILLED) {
1153 rb_bug(
"thread_join: Fixnum (%d) should not reach here.",
FIX2INT(err));
1156 else if (THROW_DATA_P(target_th->ec->errinfo)) {
1157 rb_bug(
"thread_join: THROW_DATA should not reach here.");
1164 return target_th->self;
1207thread_join_m(
int argc,
VALUE *argv,
VALUE self)
1210 rb_hrtime_t rel = 0, *limit = 0;
1221 if (
NIL_P(timeout)) {
1225 rel = rb_sec2hrtime(NUM2TIMET(timeout));
1229 limit = double2hrtime(&rel,
rb_num2dbl(timeout));
1232 return thread_join(rb_thread_ptr(self), timeout, limit);
1250thread_value(
VALUE self)
1253 thread_join(th,
Qnil, 0);
1254 if (UNDEF_P(th->value)) {
1268#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
1269 if (clock_gettime(CLOCK_MONOTONIC, ts) == 0)
1279NOINLINE(rb_hrtime_t rb_hrtime_now(
void));
1286 return rb_timespec2hrtime(&ts);
1293COMPILER_WARNING_PUSH
1294#if defined(__GNUC__) && __GNUC__ == 7 && __GNUC_MINOR__ <= 3
1295COMPILER_WARNING_IGNORED(-Wmaybe-uninitialized)
1298#define PRIu64 PRI_64_PREFIX "u"
1306hrtime_update_expire(rb_hrtime_t *timeout,
const rb_hrtime_t end)
1308 rb_hrtime_t now = rb_hrtime_now();
1310 if (now > end)
return 1;
1312 RUBY_DEBUG_LOG(
"%"PRIu64
" > %"PRIu64
"", (uint64_t)end, (uint64_t)now);
1314 *timeout = end - now;
1320sleep_hrtime(
rb_thread_t *th, rb_hrtime_t rel,
unsigned int fl)
1322 enum rb_thread_status prev_status = th->status;
1324 rb_hrtime_t end = rb_hrtime_add(rb_hrtime_now(), rel);
1326 th->status = THREAD_STOPPED;
1327 RUBY_VM_CHECK_INTS_BLOCKING(th->ec);
1328 while (th->status == THREAD_STOPPED) {
1329 native_sleep(th, &rel);
1330 woke = vm_check_ints_blocking(th->ec);
1331 if (woke && !(fl & SLEEP_SPURIOUS_CHECK))
1333 if (hrtime_update_expire(&rel, end))
1337 th->status = prev_status;
1342sleep_hrtime_until(
rb_thread_t *th, rb_hrtime_t end,
unsigned int fl)
1344 enum rb_thread_status prev_status = th->status;
1346 rb_hrtime_t rel = rb_hrtime_sub(end, rb_hrtime_now());
1348 th->status = THREAD_STOPPED;
1349 RUBY_VM_CHECK_INTS_BLOCKING(th->ec);
1350 while (th->status == THREAD_STOPPED) {
1351 native_sleep(th, &rel);
1352 woke = vm_check_ints_blocking(th->ec);
1353 if (woke && !(fl & SLEEP_SPURIOUS_CHECK))
1355 if (hrtime_update_expire(&rel, end))
1359 th->status = prev_status;
1366 enum rb_thread_status prev_status = th->status;
1367 enum rb_thread_status status;
1370 status = fl & SLEEP_DEADLOCKABLE ? THREAD_STOPPED_FOREVER : THREAD_STOPPED;
1371 th->status = status;
1373 if (!(fl & SLEEP_NO_CHECKINTS)) RUBY_VM_CHECK_INTS_BLOCKING(th->ec);
1375 while (th->status == status) {
1376 if (fl & SLEEP_DEADLOCKABLE) {
1377 rb_ractor_sleeper_threads_inc(th->ractor);
1378 rb_check_deadlock(th->ractor);
1381 native_sleep(th, 0);
1383 if (fl & SLEEP_DEADLOCKABLE) {
1384 rb_ractor_sleeper_threads_dec(th->ractor);
1386 if (fl & SLEEP_ALLOW_SPURIOUS) {
1390 woke = vm_check_ints_blocking(th->ec);
1392 if (woke && !(fl & SLEEP_SPURIOUS_CHECK)) {
1396 th->status = prev_status;
1402 RUBY_DEBUG_LOG(
"forever");
1403 sleep_forever(GET_THREAD(), SLEEP_SPURIOUS_CHECK);
1409 RUBY_DEBUG_LOG(
"deadly");
1410 sleep_forever(GET_THREAD(), SLEEP_DEADLOCKABLE|SLEEP_SPURIOUS_CHECK);
1414rb_thread_sleep_deadly_allow_spurious_wakeup(
VALUE blocker,
VALUE timeout, rb_hrtime_t end)
1417 if (scheduler !=
Qnil) {
1421 RUBY_DEBUG_LOG(
"...");
1423 sleep_hrtime_until(GET_THREAD(), end, SLEEP_SPURIOUS_CHECK);
1426 sleep_forever(GET_THREAD(), SLEEP_DEADLOCKABLE);
1436 sleep_hrtime(th, rb_timeval2hrtime(&time), SLEEP_SPURIOUS_CHECK);
1442 RUBY_VM_CHECK_INTS_BLOCKING(ec);
1455 rb_ec_check_ints(GET_EC());
1463rb_thread_check_trap_pending(
void)
1465 return rb_signal_buff_size() != 0;
1472 return (
int)RUBY_VM_INTERRUPTED(rb_thread_ptr(thval)->ec);
1482rb_thread_schedule_limits(uint32_t limits_us)
1486 RUBY_DEBUG_LOG(
"us:%u", (
unsigned int)limits_us);
1488 if (th->running_time_us >= limits_us) {
1489 RUBY_DEBUG_LOG(
"switch %s",
"start");
1491 RB_VM_SAVE_MACHINE_CONTEXT(th);
1492 thread_sched_yield(TH_SCHED(th), th);
1493 rb_ractor_thread_switch(th->ractor, th,
true);
1495 RUBY_DEBUG_LOG(
"switch %s",
"done");
1503 rb_thread_schedule_limits(0);
1504 RUBY_VM_CHECK_INTS(GET_EC());
1513#ifdef RUBY_ASSERT_CRITICAL_SECTION
1514 VM_ASSERT(ruby_assert_critical_section_entered == 0);
1516 VM_ASSERT(th == GET_THREAD());
1518 region->prev_status = th->status;
1519 if (unblock_function_set(th, ubf, arg, fail_if_interrupted)) {
1520 th->blocking_region_buffer = region;
1521 th->status = THREAD_STOPPED;
1522 rb_ractor_blocking_threads_inc(th->ractor, __FILE__, __LINE__);
1524 RUBY_DEBUG_LOG(
"thread_id:%p", (
void *)th->nt->thread_id);
1536 unblock_function_clear(th);
1538 unregister_ubf_list(th);
1540 thread_sched_to_running(TH_SCHED(th), th);
1541 rb_ractor_thread_switch(th->ractor, th,
false);
1543 th->blocking_region_buffer = 0;
1544 rb_ractor_blocking_threads_dec(th->ractor, __FILE__, __LINE__);
1545 if (th->status == THREAD_STOPPED) {
1546 th->status = region->prev_status;
1549 RUBY_DEBUG_LOG(
"end");
1553 VM_ASSERT(th == GET_THREAD());
1573 *unblock_function = ubf_select;
1581rb_nogvl(
void *(*func)(
void *),
void *data1,
1587 if (scheduler !=
Qnil) {
1592 if (!UNDEF_P(result)) {
1593 rb_errno_set(state.saved_errno);
1594 return state.result;
1602 rb_vm_t *vm = rb_ec_vm_ptr(ec);
1603 bool is_main_thread = vm->ractor.main_thread == th;
1604 int saved_errno = 0;
1606 rb_thread_resolve_unblock_function(&ubf, &data2, th);
1608 if (ubf && rb_ractor_living_thread_num(th->ractor) == 1 && is_main_thread) {
1610 vm->ubf_async_safe = 1;
1614 rb_vm_t *
volatile saved_vm = vm;
1615 BLOCKING_REGION(th, {
1617 saved_errno = rb_errno();
1621 if (is_main_thread) vm->ubf_async_safe = 0;
1624 RUBY_VM_CHECK_INTS_BLOCKING(ec);
1627 rb_errno_set(saved_errno);
1728 return rb_nogvl(func, data1, ubf, data2, 0);
1732waitfd_to_waiting_flag(
int wfd_event)
1734 return wfd_event << 1;
1737static struct ccan_list_head *
1738rb_io_blocking_operations(
struct rb_io *io)
1740 rb_serial_t fork_generation = GET_VM()->fork_gen;
1744 if (io->fork_generation != fork_generation) {
1746 io->fork_generation = fork_generation;
1765 ccan_list_add(rb_io_blocking_operations(io), &blocking_operation->list);
1771 ccan_list_del(&blocking_operation->list);
1780io_blocking_operation_exit(
VALUE _arguments)
1785 rb_io_blocking_operation_pop(arguments->io, blocking_operation);
1789 rb_fiber_t *fiber = io->closing_ec->fiber_ptr;
1791 if (thread->scheduler !=
Qnil) {
1815 VALUE wakeup_mutex = io->wakeup_mutex;
1818 blocking_operation->ec = NULL;
1823 .blocking_operation = blocking_operation
1830 rb_io_blocking_operation_pop(io, blocking_operation);
1835rb_thread_io_blocking_operation_ensure(
VALUE _argument)
1839 rb_io_blocking_operation_exit(arguments->io, arguments->blocking_operation);
1867 rb_io_blocking_operation_enter(io, &blocking_operation);
1871 .blocking_operation = &blocking_operation
1880#if defined(USE_MN_THREADS) && USE_MN_THREADS
1881 return !th_has_dedicated_nt(th) && (events || timeout) && th->blocking;
1889thread_io_wait_events(
rb_thread_t *th,
int fd,
int events,
const struct timeval *timeout)
1891#if defined(USE_MN_THREADS) && USE_MN_THREADS
1892 if (thread_io_mn_schedulable(th, events, timeout)) {
1893 rb_hrtime_t rel, *prel;
1896 rel = rb_timeval2hrtime(timeout);
1903 VM_ASSERT(prel || (events & (RB_WAITFD_IN | RB_WAITFD_OUT)));
1905 if (thread_sched_wait_events(TH_SCHED(th), th, fd, waitfd_to_waiting_flag(events), prel)) {
1919blocking_call_retryable_p(
int r,
int eno)
1921 if (r != -1)
return false;
1925#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
1935rb_thread_mn_schedulable(
VALUE thval)
1938 return th->mn_schedulable;
1942rb_thread_io_blocking_call(
struct rb_io* io, rb_blocking_function_t *func,
void *data1,
int events)
1947 RUBY_DEBUG_LOG(
"th:%u fd:%d ev:%d", rb_th_serial(th), io->
fd, events);
1950 volatile int saved_errno = 0;
1951 enum ruby_tag_type state;
1952 volatile bool prev_mn_schedulable = th->mn_schedulable;
1953 th->mn_schedulable = thread_io_mn_schedulable(th, events, NULL);
1966 rb_io_blocking_operation_enter(io, &blocking_operation);
1970 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
1971 volatile enum ruby_tag_type saved_state = state;
1973 BLOCKING_REGION(th, {
1975 saved_errno =
errno;
1976 }, ubf_select, th, FALSE);
1980 blocking_call_retryable_p((
int)val, saved_errno) &&
1981 thread_io_wait_events(th, fd, events, NULL)) {
1982 RUBY_VM_CHECK_INTS_BLOCKING(ec);
1986 RUBY_VM_CHECK_INTS_BLOCKING(ec);
1988 state = saved_state;
1992 th = rb_ec_thread_ptr(ec);
1993 th->mn_schedulable = prev_mn_schedulable;
1996 rb_io_blocking_operation_exit(io, &blocking_operation);
1999 EC_JUMP_TAG(ec, state);
2003 if (saved_errno == ETIMEDOUT) {
2007 errno = saved_errno;
2013rb_thread_io_blocking_region(
struct rb_io *io, rb_blocking_function_t *func,
void *data1)
2015 return rb_thread_io_blocking_call(io, func, data1, 0);
2060 fprintf(stderr,
"[BUG] rb_thread_call_with_gvl() is called by non-ruby thread\n");
2065 prev_unblock = th->unblock;
2068 rb_bug(
"rb_thread_call_with_gvl: called by a thread which has GVL.");
2071 blocking_region_end(th, brb);
2075 int released = blocking_region_begin(th, brb, prev_unblock.func, prev_unblock.arg, FALSE);
2077 RB_VM_SAVE_MACHINE_CONTEXT(th);
2078 thread_sched_to_waiting(TH_SCHED(th), th);
2087ruby_thread_has_gvl_p(
void)
2091 if (th && th->blocking_region_buffer == 0) {
2108thread_s_pass(
VALUE klass)
2133rb_threadptr_pending_interrupt_clear(
rb_thread_t *th)
2142 th->pending_interrupt_queue_checked = 0;
2146threadptr_check_pending_interrupt_queue(
rb_thread_t *th)
2148 if (!th->pending_interrupt_queue) {
2153enum handle_interrupt_timing {
2155 INTERRUPT_IMMEDIATE,
2156 INTERRUPT_ON_BLOCKING,
2160static enum handle_interrupt_timing
2163 if (sym == sym_immediate) {
2164 return INTERRUPT_IMMEDIATE;
2166 else if (sym == sym_on_blocking) {
2167 return INTERRUPT_ON_BLOCKING;
2169 else if (sym == sym_never) {
2170 return INTERRUPT_NEVER;
2177static enum handle_interrupt_timing
2181 long mask_stack_len =
RARRAY_LEN(th->pending_interrupt_mask_stack);
2186 for (i=0; i<mask_stack_len; i++) {
2187 mask = mask_stack[mask_stack_len-(i+1)];
2192 return rb_threadptr_pending_interrupt_from_symbol(th, mask);
2204 klass =
RBASIC(mod)->klass;
2206 else if (mod != RCLASS_ORIGIN(mod)) {
2210 if ((sym = rb_hash_aref(mask, klass)) !=
Qnil) {
2211 return rb_threadptr_pending_interrupt_from_symbol(th, sym);
2216 return INTERRUPT_NONE;
2220rb_threadptr_pending_interrupt_empty_p(
const rb_thread_t *th)
2222 return RARRAY_LEN(th->pending_interrupt_queue) == 0;
2229 for (i=0; i<
RARRAY_LEN(th->pending_interrupt_queue); i++) {
2239rb_threadptr_pending_interrupt_deque(
rb_thread_t *th,
enum handle_interrupt_timing timing)
2244 for (i=0; i<
RARRAY_LEN(th->pending_interrupt_queue); i++) {
2247 enum handle_interrupt_timing mask_timing = rb_threadptr_pending_interrupt_check_mask(th,
CLASS_OF(err));
2249 switch (mask_timing) {
2250 case INTERRUPT_ON_BLOCKING:
2251 if (timing != INTERRUPT_ON_BLOCKING) {
2255 case INTERRUPT_NONE:
2256 case INTERRUPT_IMMEDIATE:
2259 case INTERRUPT_NEVER:
2264 th->pending_interrupt_queue_checked = 1;
2268 if (rb_threadptr_pending_interrupt_empty_p(th)) {
2269 th->pending_interrupt_queue_checked = 1;
2276threadptr_pending_interrupt_active_p(
rb_thread_t *th)
2283 if (th->pending_interrupt_queue_checked) {
2287 if (rb_threadptr_pending_interrupt_empty_p(th)) {
2299 if (val != sym_immediate && val != sym_on_blocking && val != sym_never) {
2300 rb_raise(rb_eArgError,
"unknown mask signature");
2308 if (
RTEST(*maskp)) {
2310 VALUE prev = *maskp;
2311 *maskp = rb_ident_hash_new();
2316 rb_hash_aset(*maskp, key, val);
2410rb_thread_s_handle_interrupt(
VALUE self,
VALUE mask_arg)
2416 enum ruby_tag_type state;
2419 rb_raise(rb_eArgError,
"block is needed.");
2422 mask_arg = rb_to_hash_type(mask_arg);
2424 if (
OBJ_FROZEN(mask_arg) && rb_hash_compare_by_id_p(mask_arg)) {
2430 if (UNDEF_P(mask)) {
2441 rb_ary_push(th->pending_interrupt_mask_stack, mask);
2442 if (!rb_threadptr_pending_interrupt_empty_p(th)) {
2443 th->pending_interrupt_queue_checked = 0;
2444 RUBY_VM_SET_INTERRUPT(th->ec);
2447 EC_PUSH_TAG(th->ec);
2448 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
2453 rb_ary_pop(th->pending_interrupt_mask_stack);
2454 if (!rb_threadptr_pending_interrupt_empty_p(th)) {
2455 th->pending_interrupt_queue_checked = 0;
2456 RUBY_VM_SET_INTERRUPT(th->ec);
2459 RUBY_VM_CHECK_INTS(th->ec);
2462 EC_JUMP_TAG(th->ec, state);
2479rb_thread_pending_interrupt_p(
int argc,
VALUE *argv,
VALUE target_thread)
2481 rb_thread_t *target_th = rb_thread_ptr(target_thread);
2483 if (!target_th->pending_interrupt_queue) {
2486 if (rb_threadptr_pending_interrupt_empty_p(target_th)) {
2490 VALUE err = argv[0];
2492 rb_raise(
rb_eTypeError,
"class or module required for rescue clause");
2494 return RBOOL(rb_threadptr_pending_interrupt_include_p(target_th, err));
2559rb_thread_s_pending_interrupt_p(
int argc,
VALUE *argv,
VALUE self)
2561 return rb_thread_pending_interrupt_p(argc, argv, GET_THREAD()->self);
2564NORETURN(
static void rb_threadptr_to_kill(
rb_thread_t *th));
2569 VM_ASSERT(GET_THREAD() == th);
2570 rb_threadptr_pending_interrupt_clear(th);
2571 th->status = THREAD_RUNNABLE;
2573 th->ec->errinfo =
INT2FIX(TAG_FATAL);
2574 EC_JUMP_TAG(th->ec, TAG_FATAL);
2584 old = ATOMIC_LOAD_RELAXED(ec->interrupt_flag);
2587 old = ATOMIC_CAS(ec->interrupt_flag, interrupt, interrupt & ec->interrupt_mask);
2588 }
while (old != interrupt);
2589 return interrupt & (
rb_atomic_t)~ec->interrupt_mask;
2592static void threadptr_interrupt_exec_exec(
rb_thread_t *th);
2600rb_threadptr_execute_interrupts(
rb_thread_t *th,
int blocking_timing)
2603 int postponed_job_interrupt = 0;
2606 VM_ASSERT(GET_THREAD() == th);
2608 if (th->ec->raised_flag)
return ret;
2610 while ((interrupt = threadptr_get_interrupts(th)) != 0) {
2612 int timer_interrupt;
2613 int pending_interrupt;
2615 int terminate_interrupt;
2617 timer_interrupt = interrupt & TIMER_INTERRUPT_MASK;
2618 pending_interrupt = interrupt & PENDING_INTERRUPT_MASK;
2619 postponed_job_interrupt = interrupt & POSTPONED_JOB_INTERRUPT_MASK;
2620 trap_interrupt = interrupt & TRAP_INTERRUPT_MASK;
2621 terminate_interrupt = interrupt & TERMINATE_INTERRUPT_MASK;
2623 if (interrupt & VM_BARRIER_INTERRUPT_MASK) {
2627 if (postponed_job_interrupt) {
2628 rb_postponed_job_flush(th->vm);
2631 if (trap_interrupt) {
2633 if (th == th->vm->ractor.main_thread) {
2634 enum rb_thread_status prev_status = th->status;
2636 th->status = THREAD_RUNNABLE;
2638 while ((sig = rb_get_next_signal()) != 0) {
2639 ret |= rb_signal_exec(th, sig);
2642 th->status = prev_status;
2645 if (!ccan_list_empty(&th->interrupt_exec_tasks)) {
2646 enum rb_thread_status prev_status = th->status;
2648 th->status = THREAD_RUNNABLE;
2650 threadptr_interrupt_exec_exec(th);
2652 th->status = prev_status;
2657 if (pending_interrupt && threadptr_pending_interrupt_active_p(th)) {
2658 VALUE err = rb_threadptr_pending_interrupt_deque(th, blocking_timing ? INTERRUPT_ON_BLOCKING : INTERRUPT_NONE);
2659 RUBY_DEBUG_LOG(
"err:%"PRIdVALUE, err);
2665 else if (err == RUBY_FATAL_THREAD_KILLED ||
2666 err == RUBY_FATAL_THREAD_TERMINATED ||
2668 terminate_interrupt = 1;
2671 if (err == th->vm->special_exceptions[ruby_error_stream_closed]) {
2673 err = ruby_vm_special_exception_copy(err);
2676 if (th->status == THREAD_STOPPED ||
2677 th->status == THREAD_STOPPED_FOREVER)
2678 th->status = THREAD_RUNNABLE;
2683 if (terminate_interrupt) {
2684 rb_threadptr_to_kill(th);
2687 if (timer_interrupt) {
2688 uint32_t limits_us = thread_default_quantum_ms * 1000;
2690 if (th->priority > 0)
2691 limits_us <<= th->priority;
2693 limits_us >>= -th->priority;
2695 if (th->status == THREAD_RUNNABLE)
2696 th->running_time_us += 10 * 1000;
2698 VM_ASSERT(th->ec->cfp);
2702 rb_thread_schedule_limits(limits_us);
2709rb_thread_execute_interrupts(
VALUE thval)
2711 rb_threadptr_execute_interrupts(rb_thread_ptr(thval), 1);
2717 rb_threadptr_interrupt(th);
2723 if (rb_threadptr_dead(target_th)) {
2727 VALUE exception = rb_exception_setup(argc, argv);
2731 if (rb_threadptr_dead(target_th)) {
2735 rb_threadptr_pending_interrupt_enque(target_th, exception);
2736 rb_threadptr_interrupt(target_th);
2742rb_threadptr_signal_raise(
rb_thread_t *th,
int sig)
2748 rb_threadptr_raise(th->vm->ractor.main_thread, 2, argv);
2760 rb_threadptr_raise(th->vm->ractor.main_thread, 2, argv);
2766 if (ec->raised_flag & RAISED_EXCEPTION) {
2769 ec->raised_flag |= RAISED_EXCEPTION;
2776 if (!(ec->raised_flag & RAISED_EXCEPTION)) {
2779 ec->raised_flag &= ~RAISED_EXCEPTION;
2804thread_io_close_notify_all(
VALUE _io)
2809 rb_vm_t *vm = io->closing_ec->thread_ptr->vm;
2810 VALUE error = vm->special_exceptions[ruby_error_stream_closed];
2813 ccan_list_for_each(rb_io_blocking_operations(io), blocking_operation, list) {
2821 if (thread->scheduler !=
Qnil) {
2827 rb_threadptr_pending_interrupt_enque(thread, error);
2828 rb_threadptr_interrupt(thread);
2835 return (
VALUE)count;
2839rb_thread_io_close_interrupt(
struct rb_io *io)
2842 if (io->closing_ec) {
2847 if (ccan_list_empty(rb_io_blocking_operations(io))) {
2853 io->closing_ec = ec;
2857 rb_mutex_allow_trap(io->wakeup_mutex, 1);
2862 return (
size_t)result;
2866rb_thread_io_close_wait(
struct rb_io* io)
2868 VALUE wakeup_mutex = io->wakeup_mutex;
2876 while (!ccan_list_empty(rb_io_blocking_operations(io))) {
2882 io->wakeup_mutex =
Qnil;
2883 io->closing_ec = NULL;
2889 rb_warn(
"rb_thread_fd_close is deprecated (and is now a no-op).");
2914thread_raise_m(
int argc,
VALUE *argv,
VALUE self)
2919 threadptr_check_pending_interrupt_queue(target_th);
2920 rb_threadptr_raise(target_th, argc, argv);
2923 if (current_th == target_th) {
2924 RUBY_VM_CHECK_INTS(target_th->ec);
2949 if (target_th->to_kill || target_th->status == THREAD_KILLED) {
2952 if (target_th == target_th->vm->ractor.main_thread) {
2956 RUBY_DEBUG_LOG(
"target_th:%u", rb_th_serial(target_th));
2958 if (target_th == GET_THREAD()) {
2960 rb_threadptr_to_kill(target_th);
2963 threadptr_check_pending_interrupt_queue(target_th);
2964 rb_threadptr_pending_interrupt_enque(target_th, RUBY_FATAL_THREAD_KILLED);
2965 rb_threadptr_interrupt(target_th);
2972rb_thread_to_be_killed(
VALUE thread)
2976 if (target_th->to_kill || target_th->status == THREAD_KILLED) {
3052 if (target_th->status == THREAD_KILLED)
return Qnil;
3054 rb_threadptr_ready(target_th);
3056 if (target_th->status == THREAD_STOPPED ||
3057 target_th->status == THREAD_STOPPED_FOREVER) {
3058 target_th->status = THREAD_RUNNABLE;
3100 "stopping only thread\n\tnote: use sleep to stop forever");
3133 return rb_ractor_thread_list();
3159 return rb_thread_list();
3165 return GET_THREAD()->self;
3178thread_s_current(
VALUE klass)
3186 return GET_RACTOR()->threads.main->self;
3197rb_thread_s_main(
VALUE klass)
3224rb_thread_s_abort_exc(
VALUE _)
3226 return RBOOL(GET_THREAD()->vm->thread_abort_on_exception);
3261rb_thread_s_abort_exc_set(
VALUE self,
VALUE val)
3263 GET_THREAD()->vm->thread_abort_on_exception =
RTEST(val);
3284rb_thread_abort_exc(
VALUE thread)
3286 return RBOOL(rb_thread_ptr(thread)->abort_on_exception);
3304rb_thread_abort_exc_set(
VALUE thread,
VALUE val)
3306 rb_thread_ptr(thread)->abort_on_exception =
RTEST(val);
3354rb_thread_s_report_exc(
VALUE _)
3356 return RBOOL(GET_THREAD()->vm->thread_report_on_exception);
3391rb_thread_s_report_exc_set(
VALUE self,
VALUE val)
3393 GET_THREAD()->vm->thread_report_on_exception =
RTEST(val);
3410rb_thread_s_ignore_deadlock(
VALUE _)
3412 return RBOOL(GET_THREAD()->vm->thread_ignore_deadlock);
3437rb_thread_s_ignore_deadlock_set(
VALUE self,
VALUE val)
3439 GET_THREAD()->vm->thread_ignore_deadlock =
RTEST(val);
3461rb_thread_report_exc(
VALUE thread)
3463 return RBOOL(rb_thread_ptr(thread)->report_on_exception);
3481rb_thread_report_exc_set(
VALUE thread,
VALUE val)
3483 rb_thread_ptr(thread)->report_on_exception =
RTEST(val);
3498rb_thread_group(
VALUE thread)
3500 return rb_thread_ptr(thread)->thgroup;
3506 switch (th->status) {
3507 case THREAD_RUNNABLE:
3508 return th->to_kill ?
"aborting" :
"run";
3509 case THREAD_STOPPED_FOREVER:
3510 if (detail)
return "sleep_forever";
3511 case THREAD_STOPPED:
3523 return th->status == THREAD_KILLED;
3559rb_thread_status(
VALUE thread)
3563 if (rb_threadptr_dead(target_th)) {
3564 if (!
NIL_P(target_th->ec->errinfo) &&
3565 !
FIXNUM_P(target_th->ec->errinfo)) {
3573 return rb_str_new2(thread_status_name(target_th, FALSE));
3593rb_thread_alive_p(
VALUE thread)
3595 return RBOOL(!thread_finished(rb_thread_ptr(thread)));
3613rb_thread_stop_p(
VALUE thread)
3617 if (rb_threadptr_dead(th)) {
3620 return RBOOL(th->status == THREAD_STOPPED || th->status == THREAD_STOPPED_FOREVER);
3631rb_thread_getname(
VALUE thread)
3633 return rb_thread_ptr(thread)->name;
3652 enc = rb_enc_get(name);
3653 if (!rb_enc_asciicompat(enc)) {
3654 rb_raise(rb_eArgError,
"ASCII incompatible encoding (%s)",
3659 target_th->name = name;
3660 if (threadptr_initialized(target_th) && target_th->has_dedicated_nt) {
3661 native_set_another_thread_name(target_th->nt->thread_id, name);
3666#if USE_NATIVE_THREAD_NATIVE_THREAD_ID
3690rb_thread_native_thread_id(
VALUE thread)
3693 if (rb_threadptr_dead(target_th))
return Qnil;
3694 return native_thread_native_thread_id(target_th);
3697# define rb_thread_native_thread_id rb_f_notimplement
3708rb_thread_to_s(
VALUE thread)
3715 status = thread_status_name(target_th, TRUE);
3716 str = rb_sprintf(
"#<%"PRIsVALUE
":%p", cname, (
void *)thread);
3717 if (!
NIL_P(target_th->name)) {
3718 rb_str_catf(str,
"@%"PRIsVALUE, target_th->name);
3720 if ((loc = threadptr_invoke_proc_location(target_th)) !=
Qnil) {
3721 rb_str_catf(str,
" %"PRIsVALUE
":%"PRIsVALUE,
3724 rb_str_catf(str,
" %s>", status);
3730#define recursive_key id__recursive_key__
3735 if (
id == recursive_key) {
3736 return th->ec->local_storage_recursive_hash;
3740 struct rb_id_table *local_storage = th->ec->local_storage;
3742 if (local_storage != NULL && rb_id_table_lookup(local_storage,
id, &val)) {
3754 return threadptr_local_aref(rb_thread_ptr(thread),
id);
3821 if (!
id)
return Qnil;
3839rb_thread_fetch(
int argc,
VALUE *argv,
VALUE self)
3850 if (block_given && argc == 2) {
3851 rb_warn(
"block supersedes default value argument");
3856 if (
id == recursive_key) {
3857 return target_th->ec->local_storage_recursive_hash;
3859 else if (
id && target_th->ec->local_storage &&
3860 rb_id_table_lookup(target_th->ec->local_storage,
id, &val)) {
3863 else if (block_given) {
3866 else if (argc == 1) {
3867 rb_key_err_raise(rb_sprintf(
"key not found: %+"PRIsVALUE, key), self, key);
3877 if (
id == recursive_key) {
3878 th->ec->local_storage_recursive_hash = val;
3882 struct rb_id_table *local_storage = th->ec->local_storage;
3885 if (!local_storage)
return Qnil;
3886 rb_id_table_delete(local_storage,
id);
3890 if (local_storage == NULL) {
3891 th->ec->local_storage = local_storage = rb_id_table_create(0);
3893 rb_id_table_insert(local_storage,
id, val);
3906 return threadptr_local_aset(rb_thread_ptr(thread),
id, val);
3957rb_thread_variable_get(
VALUE thread,
VALUE key)
3962 if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
3965 locals = rb_thread_local_storage(thread);
3966 return rb_hash_aref(locals, symbol);
3987 locals = rb_thread_local_storage(thread);
4009 struct rb_id_table *local_storage = rb_thread_ptr(self)->ec->local_storage;
4011 if (!
id || local_storage == NULL) {
4014 return RBOOL(rb_id_table_lookup(local_storage,
id, &val));
4017static enum rb_id_table_iterator_result
4018thread_keys_i(
ID key,
VALUE value,
void *ary)
4021 return ID_TABLE_CONTINUE;
4028 return rb_ractor_living_thread_num(GET_RACTOR()) == 1;
4046rb_thread_keys(
VALUE self)
4048 struct rb_id_table *local_storage = rb_thread_ptr(self)->ec->local_storage;
4051 if (local_storage) {
4052 rb_id_table_foreach(local_storage, thread_keys_i, (
void *)ary);
4082rb_thread_variables(
VALUE thread)
4088 if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
4091 locals = rb_thread_local_storage(thread);
4119 if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
4122 locals = rb_thread_local_storage(thread);
4124 return RBOOL(rb_hash_lookup(locals, symbol) !=
Qnil);
4143rb_thread_priority(
VALUE thread)
4145 return INT2NUM(rb_thread_ptr(thread)->priority);
4176rb_thread_priority_set(
VALUE thread,
VALUE prio)
4181#if USE_NATIVE_THREAD_PRIORITY
4182 target_th->priority =
NUM2INT(prio);
4183 native_thread_apply_priority(th);
4186 if (priority > RUBY_THREAD_PRIORITY_MAX) {
4187 priority = RUBY_THREAD_PRIORITY_MAX;
4189 else if (priority < RUBY_THREAD_PRIORITY_MIN) {
4190 priority = RUBY_THREAD_PRIORITY_MIN;
4192 target_th->priority = (int8_t)priority;
4194 return INT2NUM(target_th->priority);
4199#if defined(NFDBITS) && defined(HAVE_RB_FD_INIT)
4235 FD_ZERO(fds->
fdset);
4241 size_t size = howmany(
rb_fd_max(src), NFDBITS) *
sizeof(fd_mask);
4243 if (size <
sizeof(fd_set))
4244 size =
sizeof(fd_set);
4268 size_t m = howmany(n + 1, NFDBITS) *
sizeof(fd_mask);
4269 size_t o = howmany(fds->
maxfd, NFDBITS) *
sizeof(fd_mask);
4271 if (m <
sizeof(fd_set)) m =
sizeof(fd_set);
4272 if (o <
sizeof(fd_set)) o =
sizeof(fd_set);
4276 memset((
char *)fds->
fdset + o, 0, m - o);
4285 FD_SET(n, fds->
fdset);
4291 if (n >= fds->
maxfd)
return;
4292 FD_CLR(n, fds->
fdset);
4298 if (n >= fds->
maxfd)
return 0;
4299 return FD_ISSET(n, fds->
fdset) != 0;
4305 size_t size = howmany(max, NFDBITS) *
sizeof(fd_mask);
4307 if (size <
sizeof(fd_set)) size =
sizeof(fd_set);
4310 memcpy(dst->
fdset, src, size);
4316 size_t size = howmany(
rb_fd_max(src), NFDBITS) *
sizeof(fd_mask);
4318 if (size <
sizeof(fd_set))
4319 size =
sizeof(fd_set);
4328 fd_set *r = NULL, *w = NULL, *e = NULL;
4341 return select(n, r, w, e, timeout);
4344#define rb_fd_no_init(fds) ((void)((fds)->fdset = 0), (void)((fds)->maxfd = 0))
4351#define FD_ZERO(f) rb_fd_zero(f)
4352#define FD_SET(i, f) rb_fd_set((i), (f))
4353#define FD_CLR(i, f) rb_fd_clr((i), (f))
4354#define FD_ISSET(i, f) rb_fd_isset((i), (f))
4356#elif defined(_WIN32)
4361 set->
capa = FD_SETSIZE;
4363 FD_ZERO(set->
fdset);
4385 SOCKET s = rb_w32_get_osfhandle(fd);
4387 for (i = 0; i < set->
fdset->fd_count; i++) {
4388 if (set->
fdset->fd_array[i] == s) {
4392 if (set->
fdset->fd_count >= (
unsigned)set->
capa) {
4393 set->
capa = (set->
fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
4395 rb_xrealloc_mul_add(
4396 set->
fdset, set->
capa,
sizeof(SOCKET),
sizeof(
unsigned int));
4398 set->
fdset->fd_array[set->
fdset->fd_count++] = s;
4406#define FD_ZERO(f) rb_fd_zero(f)
4407#define FD_SET(i, f) rb_fd_set((i), (f))
4408#define FD_CLR(i, f) rb_fd_clr((i), (f))
4409#define FD_ISSET(i, f) rb_fd_isset((i), (f))
4411#define rb_fd_no_init(fds) (void)((fds)->fdset = 0)
4415#ifndef rb_fd_no_init
4416#define rb_fd_no_init(fds) (void)(fds)
4420wait_retryable(
volatile int *result,
int errnum, rb_hrtime_t *rel, rb_hrtime_t end)
4430 if (rel && hrtime_update_expire(rel, end)) {
4440 return !hrtime_update_expire(rel, end);
4460select_set_free(
VALUE p)
4475 volatile int result = 0;
4477 rb_hrtime_t *to, rel, end = 0;
4479 timeout_prepare(&to, &rel, &end, set->timeout);
4480 volatile rb_hrtime_t endtime = end;
4481#define restore_fdset(dst, src) \
4482 ((dst) ? rb_fd_dup(dst, src) : (void)0)
4483#define do_select_update() \
4484 (restore_fdset(set->rset, &set->orig_rset), \
4485 restore_fdset(set->wset, &set->orig_wset), \
4486 restore_fdset(set->eset, &set->orig_eset), \
4492 BLOCKING_REGION(set->th, {
4495 if (!RUBY_VM_INTERRUPTED(set->th->ec)) {
4496 result = native_fd_select(set->max,
4497 set->rset, set->wset, set->eset,
4498 rb_hrtime2timeval(&tv, to), set->th);
4499 if (result < 0) lerrno = errno;
4501 }, ubf_select, set->th, TRUE);
4503 RUBY_VM_CHECK_INTS_BLOCKING(set->th->ec);
4504 }
while (wait_retryable(&result, lerrno, to, endtime) && do_select_update());
4506 RUBY_VM_CHECK_INTS_BLOCKING(set->th->ec);
4512 return (
VALUE)result;
4521 set.th = GET_THREAD();
4522 RUBY_VM_CHECK_INTS_BLOCKING(set.th->ec);
4527 set.timeout = timeout;
4529 if (!set.rset && !set.wset && !set.eset) {
4538#define fd_init_copy(f) do { \
4540 rb_fd_resize(set.max - 1, set.f); \
4541 if (&set.orig_##f != set.f) { \
4542 rb_fd_init_copy(&set.orig_##f, set.f); \
4546 rb_fd_no_init(&set.orig_##f); \
4560#define POLLIN_SET (POLLRDNORM | POLLRDBAND | POLLIN | POLLHUP | POLLERR)
4561#define POLLOUT_SET (POLLWRBAND | POLLWRNORM | POLLOUT | POLLERR)
4562#define POLLEX_SET (POLLPRI)
4565# define POLLERR_SET (0)
4569wait_for_single_fd_blocking_region(
rb_thread_t *th,
struct pollfd *fds, nfds_t nfds,
4570 rb_hrtime_t *
const to,
volatile int *lerrno)
4573 volatile int result = 0;
4576 BLOCKING_REGION(th, {
4577 if (!RUBY_VM_INTERRUPTED(th->ec)) {
4578 result = ppoll(fds, nfds, rb_hrtime2timespec(&ts, to), 0);
4579 if (result < 0) *lerrno = errno;
4581 }, ubf_select, th, TRUE);
4589thread_io_wait(
struct rb_io *io,
int fd,
int events,
struct timeval *timeout)
4591 struct pollfd fds[1] = {{
4593 .events = (short)events,
4596 volatile int result = 0;
4599 enum ruby_tag_type state;
4600 volatile int lerrno;
4606 blocking_operation.ec = ec;
4607 rb_io_blocking_operation_enter(io, &blocking_operation);
4610 if (timeout == NULL && thread_io_wait_events(th, fd, events, NULL)) {
4613 fds[0].revents = events;
4618 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
4619 rb_hrtime_t *to, rel, end = 0;
4620 RUBY_VM_CHECK_INTS_BLOCKING(ec);
4621 timeout_prepare(&to, &rel, &end, timeout);
4623 nfds = numberof(fds);
4624 result = wait_for_single_fd_blocking_region(th, fds, nfds, to, &lerrno);
4626 RUBY_VM_CHECK_INTS_BLOCKING(ec);
4627 }
while (wait_retryable(&result, lerrno, to, end));
4629 RUBY_VM_CHECK_INTS_BLOCKING(ec);
4636 rb_io_blocking_operation_exit(io, &blocking_operation);
4640 EC_JUMP_TAG(ec, state);
4648 if (fds[0].revents & POLLNVAL) {
4658 if (fds[0].revents & POLLIN_SET)
4659 result |= RB_WAITFD_IN;
4660 if (fds[0].revents & POLLOUT_SET)
4661 result |= RB_WAITFD_OUT;
4662 if (fds[0].revents & POLLEX_SET)
4663 result |= RB_WAITFD_PRI;
4666 if (fds[0].revents & POLLERR_SET)
4687select_single(
VALUE ptr)
4693 args->read, args->write, args->except, args->tv);
4695 args->as.error =
errno;
4698 if (args->read &&
rb_fd_isset(args->as.fd, args->read))
4700 if (args->write &&
rb_fd_isset(args->as.fd, args->write))
4702 if (args->except &&
rb_fd_isset(args->as.fd, args->except))
4709select_single_cleanup(
VALUE ptr)
4713 if (args->blocking_operation) {
4714 rb_io_blocking_operation_exit(args->io, args->blocking_operation);
4737thread_io_wait(
struct rb_io *io,
int fd,
int events,
struct timeval *timeout)
4746 blocking_operation.ec = GET_EC();
4747 rb_io_blocking_operation_enter(io, &blocking_operation);
4748 args.blocking_operation = &blocking_operation;
4752 blocking_operation.ec = NULL;
4753 args.blocking_operation = NULL;
4757 args.read = (events & RB_WAITFD_IN) ? init_set_fd(fd, &rfds) : NULL;
4758 args.write = (events & RB_WAITFD_OUT) ? init_set_fd(fd, &wfds) : NULL;
4759 args.except = (events & RB_WAITFD_PRI) ? init_set_fd(fd, &efds) : NULL;
4762 int result = (int)
rb_ensure(select_single, ptr, select_single_cleanup, ptr);
4764 errno = args.as.error;
4771rb_thread_wait_for_single_fd(
int fd,
int events,
struct timeval *timeout)
4773 return thread_io_wait(NULL, fd, events, timeout);
4777rb_thread_io_wait(
struct rb_io *io,
int events,
struct timeval * timeout)
4779 return thread_io_wait(io, io->
fd, events, timeout);
4786#ifdef USE_CONSERVATIVE_STACK_END
4788rb_gc_set_stack_end(
VALUE **stack_end_p)
4791COMPILER_WARNING_PUSH
4792#if RBIMPL_COMPILER_IS(GCC)
4793COMPILER_WARNING_IGNORED(-Wdangling-pointer);
4795 *stack_end_p = &stack_end;
4808 if (rb_signal_buff_size() > 0) {
4810 threadptr_trap_interrupt(mth);
4815async_bug_fd(
const char *mesg,
int errno_arg,
int fd)
4818 size_t n = strlcpy(buff, mesg,
sizeof(buff));
4819 if (n <
sizeof(buff)-3) {
4822 rb_async_bug_errno(buff, errno_arg);
4827consume_communication_pipe(
int fd)
4833 static char buff[1024];
4839 result = read(fd, buff,
sizeof(buff));
4841 RUBY_DEBUG_LOG(
"resultf:%d buff:%lu", (
int)result, (
unsigned long)buff[0]);
4843 RUBY_DEBUG_LOG(
"result:%d", (
int)result);
4847 if (USE_EVENTFD || result < (ssize_t)
sizeof(buff)) {
4851 else if (result == 0) {
4854 else if (result < 0) {
4860#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
4865 async_bug_fd(
"consume_communication_pipe: read", e, fd);
4872rb_thread_stop_timer_thread(
void)
4874 if (TIMER_THREAD_CREATED_P() && native_stop_timer_thread()) {
4875 native_reset_timer_thread();
4880rb_thread_reset_timer_thread(
void)
4882 native_reset_timer_thread();
4886rb_thread_start_timer_thread(
void)
4889 rb_thread_create_timer_thread();
4893clear_coverage_i(st_data_t key, st_data_t val, st_data_t dummy)
4901 if (GET_VM()->coverage_mode & COVERAGE_TARGET_ONESHOT_LINES) {
4923rb_clear_coverages(
void)
4925 VALUE coverages = rb_get_coverages();
4926 if (
RTEST(coverages)) {
4931#if defined(HAVE_WORKING_FORK)
4939 vm->ractor.main_ractor = r;
4940 vm->ractor.main_thread = th;
4941 r->threads.main = th;
4942 r->status_ = ractor_created;
4944 thread_sched_atfork(TH_SCHED(th));
4949 ccan_list_for_each(&vm->ractor.set, r, vmlr_node) {
4950 if (r != vm->ractor.main_ractor) {
4951 rb_ractor_terminate_atfork(vm, r);
4953 ccan_list_for_each(&r->threads.set, i, lt_node) {
4957 rb_vm_living_threads_init(vm);
4959 rb_ractor_atfork(vm, th);
4960 rb_vm_postponed_job_atfork();
4964 ccan_list_head_init(&th->interrupt_exec_tasks);
4967 rb_ractor_sleeper_threads_clear(th->ractor);
4968 rb_clear_coverages();
4971 rb_thread_reset_timer_thread();
4972 rb_thread_start_timer_thread();
4974 VM_ASSERT(vm->ractor.blocking_cnt == 0);
4975 VM_ASSERT(vm->ractor.cnt == 1);
4981 if (th != current_th) {
4983 rb_mutex_abandon_keeping_mutexes(th);
4984 rb_mutex_abandon_locking_mutex(th);
4985 thread_cleanup_func(th, TRUE);
4994 rb_threadptr_pending_interrupt_clear(th);
4995 rb_thread_atfork_internal(th, terminate_atfork_i);
4996 th->join_list = NULL;
4997 rb_fiber_atfork(th);
5006 if (th != current_th) {
5007 thread_cleanup_func_before_exec(th);
5015 rb_thread_atfork_internal(th, terminate_atfork_before_exec_i);
5040 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE
5063thgroup_s_alloc(
VALUE klass)
5084thgroup_list(
VALUE group)
5090 ccan_list_for_each(&r->threads.set, th, lt_node) {
5091 if (th->thgroup == group) {
5116thgroup_enclose(
VALUE group)
5135thgroup_enclosed_p(
VALUE group)
5140 return RBOOL(data->enclosed);
5180 if (data->enclosed) {
5188 if (data->enclosed) {
5190 "can't move from the enclosed thread group");
5193 target_th->thgroup = group;
5201thread_shield_mark(
void *ptr)
5203 rb_gc_mark((
VALUE)ptr);
5208 {thread_shield_mark, 0, 0,},
5209 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
5213thread_shield_alloc(
VALUE klass)
5218#define GetThreadShieldPtr(obj) ((VALUE)rb_check_typeddata((obj), &thread_shield_data_type))
5219#define THREAD_SHIELD_WAITING_MASK (((FL_USER19-1)&~(FL_USER0-1))|FL_USER19)
5220#define THREAD_SHIELD_WAITING_SHIFT (FL_USHIFT)
5221#define THREAD_SHIELD_WAITING_MAX (THREAD_SHIELD_WAITING_MASK>>THREAD_SHIELD_WAITING_SHIFT)
5222STATIC_ASSERT(THREAD_SHIELD_WAITING_MAX, THREAD_SHIELD_WAITING_MAX <= UINT_MAX);
5223static inline unsigned int
5224rb_thread_shield_waiting(
VALUE b)
5226 return ((
RBASIC(b)->flags&THREAD_SHIELD_WAITING_MASK)>>THREAD_SHIELD_WAITING_SHIFT);
5230rb_thread_shield_waiting_inc(
VALUE b)
5232 unsigned int w = rb_thread_shield_waiting(b);
5234 if (w > THREAD_SHIELD_WAITING_MAX)
5236 RBASIC(b)->flags &= ~THREAD_SHIELD_WAITING_MASK;
5237 RBASIC(b)->flags |= ((
VALUE)w << THREAD_SHIELD_WAITING_SHIFT);
5241rb_thread_shield_waiting_dec(
VALUE b)
5243 unsigned int w = rb_thread_shield_waiting(b);
5246 RBASIC(b)->flags &= ~THREAD_SHIELD_WAITING_MASK;
5247 RBASIC(b)->flags |= ((
VALUE)w << THREAD_SHIELD_WAITING_SHIFT);
5251rb_thread_shield_new(
void)
5253 VALUE thread_shield = thread_shield_alloc(rb_cThreadShield);
5255 return thread_shield;
5259rb_thread_shield_owned(
VALUE self)
5261 VALUE mutex = GetThreadShieldPtr(self);
5262 if (!mutex)
return false;
5266 return m->fiber_serial == rb_fiber_serial(GET_EC()->fiber_ptr);
5278rb_thread_shield_wait(
VALUE self)
5280 VALUE mutex = GetThreadShieldPtr(self);
5283 if (!mutex)
return Qfalse;
5284 m = mutex_ptr(mutex);
5285 if (m->fiber_serial == rb_fiber_serial(GET_EC()->fiber_ptr))
return Qnil;
5286 rb_thread_shield_waiting_inc(self);
5288 rb_thread_shield_waiting_dec(self);
5291 return rb_thread_shield_waiting(self) > 0 ?
Qnil :
Qfalse;
5295thread_shield_get_mutex(
VALUE self)
5297 VALUE mutex = GetThreadShieldPtr(self);
5299 rb_raise(
rb_eThreadError,
"destroyed thread shield - %p", (
void *)self);
5307rb_thread_shield_release(
VALUE self)
5309 VALUE mutex = thread_shield_get_mutex(self);
5311 return RBOOL(rb_thread_shield_waiting(self) > 0);
5318rb_thread_shield_destroy(
VALUE self)
5320 VALUE mutex = thread_shield_get_mutex(self);
5323 return RBOOL(rb_thread_shield_waiting(self) > 0);
5329 return th->ec->local_storage_recursive_hash;
5335 th->ec->local_storage_recursive_hash = hash;
5347recursive_list_access(
VALUE sym)
5350 VALUE hash = threadptr_recursive_hash(th);
5353 hash = rb_ident_hash_new();
5354 threadptr_recursive_hash_set(th, hash);
5358 list = rb_hash_aref(hash, sym);
5361 list = rb_ident_hash_new();
5362 rb_hash_aset(hash, sym, list);
5376#if SIZEOF_LONG == SIZEOF_VOIDP
5377 #define OBJ_ID_EQL(obj_id, other) ((obj_id) == (other))
5378#elif SIZEOF_LONG_LONG == SIZEOF_VOIDP
5379 #define OBJ_ID_EQL(obj_id, other) (RB_BIGNUM_TYPE_P((obj_id)) ? \
5380 rb_big_eql((obj_id), (other)) : ((obj_id) == (other)))
5383 VALUE pair_list = rb_hash_lookup2(list, obj,
Qundef);
5384 if (UNDEF_P(pair_list))
5386 if (paired_obj_id) {
5388 if (!OBJ_ID_EQL(paired_obj_id, pair_list))
5392 if (
NIL_P(rb_hash_lookup(pair_list, paired_obj_id)))
5414 rb_hash_aset(list, obj,
Qtrue);
5416 else if (UNDEF_P(pair_list = rb_hash_lookup2(list, obj,
Qundef))) {
5417 rb_hash_aset(list, obj, paired_obj);
5421 VALUE other_paired_obj = pair_list;
5422 pair_list = rb_hash_new();
5423 rb_hash_aset(pair_list, other_paired_obj,
Qtrue);
5424 rb_hash_aset(list, obj, pair_list);
5426 rb_hash_aset(pair_list, paired_obj,
Qtrue);
5442 VALUE pair_list = rb_hash_lookup2(list, obj,
Qundef);
5443 if (UNDEF_P(pair_list)) {
5447 rb_hash_delete_entry(pair_list, paired_obj);
5453 rb_hash_delete_entry(list, obj);
5469 return (*p->func)(p->obj, p->arg, FALSE);
5490 p.list = recursive_list_access(sym);
5494 outermost = outer && !recursive_check(p.list,
ID2SYM(recursive_key), 0);
5496 if (recursive_check(p.list, p.obj, pairid)) {
5497 if (outer && !outermost) {
5500 return (*func)(obj, arg, TRUE);
5503 enum ruby_tag_type state;
5508 recursive_push(p.list,
ID2SYM(recursive_key), 0);
5509 recursive_push(p.list, p.obj, p.pairid);
5510 result = rb_catch_protect(p.list, exec_recursive_i, (
VALUE)&p, &state);
5511 if (!recursive_pop(p.list, p.obj, p.pairid))
goto invalid;
5512 if (!recursive_pop(p.list,
ID2SYM(recursive_key), 0))
goto invalid;
5513 if (state != TAG_NONE) EC_JUMP_TAG(GET_EC(), state);
5514 if (result == p.list) {
5515 result = (*func)(obj, arg, TRUE);
5520 recursive_push(p.list, p.obj, p.pairid);
5521 EC_PUSH_TAG(GET_EC());
5522 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
5523 ret = (*func)(obj, arg, FALSE);
5526 if (!recursive_pop(p.list, p.obj, p.pairid)) {
5529 if (state != TAG_NONE) EC_JUMP_TAG(GET_EC(), state);
5538 "for %+"PRIsVALUE
" in %+"PRIsVALUE,
5562 return exec_recursive(func, obj, rb_memory_id(paired_obj), arg, 0,
rb_frame_last_func());
5580 return exec_recursive(func, obj, 0, arg, 1, mid);
5592 return exec_recursive(func, obj, rb_memory_id(paired_obj), arg, 1,
rb_frame_last_func());
5604rb_thread_backtrace_m(
int argc,
VALUE *argv,
VALUE thval)
5606 return rb_vm_thread_backtrace(argc, argv, thval);
5621rb_thread_backtrace_locations_m(
int argc,
VALUE *argv,
VALUE thval)
5623 return rb_vm_thread_backtrace_locations(argc, argv, thval);
5627Init_Thread_Mutex(
void)
5716 rb_vm_register_special_exception(ruby_error_stream_closed,
rb_eIOError,
5717 "stream closed in another thread");
5726 const char * ptr = getenv(
"RUBY_THREAD_TIMESLICE");
5729 long quantum = strtol(ptr, NULL, 0);
5730 if (quantum > 0 && !(SIZEOF_LONG > 4 && quantum > UINT32_MAX)) {
5731 thread_default_quantum_ms = (uint32_t)quantum;
5734 fprintf(stderr,
"Ignored RUBY_THREAD_TIMESLICE=%s\n", ptr);
5739 th->thgroup = th->ractor->thgroup_default =
rb_obj_alloc(cThGroup);
5740 rb_define_const(cThGroup,
"Default", th->thgroup);
5750#ifdef HAVE_PTHREAD_NP_H
5751 VM_ASSERT(TH_SCHED(th)->running == th);
5758 th->pending_interrupt_queue_checked = 0;
5763 rb_thread_create_timer_thread();
5779#ifdef NON_SCALAR_THREAD_ID
5780 #define thread_id_str(th) (NULL)
5782 #define thread_id_str(th) ((void *)(uintptr_t)(th)->nt->thread_id)
5791 rb_str_catf(msg,
"\n%d threads, %d sleeps current:%p main thread:%p\n",
5792 rb_ractor_living_thread_num(r), rb_ractor_sleeper_thread_num(r),
5793 (
void *)GET_THREAD(), (
void *)r->threads.main);
5795 ccan_list_for_each(&r->threads.set, th, lt_node) {
5796 rb_str_catf(msg,
"* %+"PRIsVALUE
"\n rb_thread_t:%p "
5798 th->self, (
void *)th, th->nt ? thread_id_str(th) :
"N/A", th->ec->interrupt_flag);
5800 if (th->locking_mutex) {
5801 rb_mutex_t *mutex = mutex_ptr(th->locking_mutex);
5802 rb_str_catf(msg,
" mutex:%llu cond:%"PRIuSIZE,
5803 (
unsigned long long)mutex->fiber_serial, rb_mutex_num_waiting(mutex));
5809 rb_str_catf(msg,
"\n depended by: tb_thread_id:%p", (
void *)list->thread);
5813 rb_str_catf(msg,
"\n ");
5814 rb_str_concat(msg,
rb_ary_join(rb_ec_backtrace_str_ary(th->ec, RUBY_BACKTRACE_START, RUBY_ALL_BACKTRACE_LINES), sep));
5815 rb_str_catf(msg,
"\n");
5822 if (GET_THREAD()->vm->thread_ignore_deadlock)
return;
5824#ifdef RUBY_THREAD_PTHREAD_H
5825 if (r->threads.sched.readyq_cnt > 0)
return;
5828 int sleeper_num = rb_ractor_sleeper_thread_num(r);
5829 int ltnum = rb_ractor_living_thread_num(r);
5831 if (ltnum > sleeper_num)
return;
5832 if (ltnum < sleeper_num) rb_bug(
"sleeper must not be more than vm_living_thread_num(vm)");
5837 ccan_list_for_each(&r->threads.set, th, lt_node) {
5838 if (th->status != THREAD_STOPPED_FOREVER || RUBY_VM_INTERRUPTED(th->ec)) {
5841 else if (th->locking_mutex) {
5842 rb_mutex_t *mutex = mutex_ptr(th->locking_mutex);
5843 if (mutex->fiber_serial == rb_fiber_serial(th->ec->fiber_ptr) || (!mutex->fiber_serial && !ccan_list_empty(&mutex->waitq))) {
5854 argv[1] =
rb_str_new2(
"No live threads left. Deadlock?");
5855 debug_deadlock_check(r, argv[1]);
5856 rb_ractor_sleeper_threads_dec(GET_RACTOR());
5857 rb_threadptr_raise(r->threads.main, 2, argv);
5865 VALUE coverage = rb_iseq_coverage(cfp->iseq);
5870 VM_ASSERT(line >= 0);
5874 if (GET_VM()->coverage_mode & COVERAGE_TARGET_ONESHOT_LINES) {
5875 rb_iseq_clear_event_flags(cfp->iseq, cfp->pc - ISEQ_BODY(cfp->iseq)->iseq_encoded - 1, RUBY_EVENT_COVERAGE_LINE);
5896 VALUE coverage = rb_iseq_coverage(cfp->iseq);
5900 long pc = cfp->pc - ISEQ_BODY(cfp->iseq)->iseq_encoded - 1;
5915 VALUE path, beg_pos_lineno, beg_pos_column, end_pos_lineno, end_pos_column;
5917 if (!me->def)
return NULL;
5920 switch (me->def->type) {
5921 case VM_METHOD_TYPE_ISEQ: {
5924 path = rb_iseq_path(iseq);
5925 beg_pos_lineno =
INT2FIX(loc->code_location.beg_pos.lineno);
5926 beg_pos_column =
INT2FIX(loc->code_location.beg_pos.column);
5927 end_pos_lineno =
INT2FIX(loc->code_location.end_pos.lineno);
5928 end_pos_column =
INT2FIX(loc->code_location.end_pos.column);
5931 case VM_METHOD_TYPE_BMETHOD: {
5932 const rb_iseq_t *iseq = rb_proc_get_iseq(me->def->body.bmethod.proc, 0);
5935 rb_iseq_check(iseq);
5936 path = rb_iseq_path(iseq);
5937 loc = &ISEQ_BODY(iseq)->location;
5938 beg_pos_lineno =
INT2FIX(loc->code_location.beg_pos.lineno);
5939 beg_pos_column =
INT2FIX(loc->code_location.beg_pos.column);
5940 end_pos_lineno =
INT2FIX(loc->code_location.end_pos.lineno);
5941 end_pos_column =
INT2FIX(loc->code_location.end_pos.column);
5946 case VM_METHOD_TYPE_ALIAS:
5947 me = me->def->body.alias.original_me;
5949 case VM_METHOD_TYPE_REFINED:
5950 me = me->def->body.refined.orig_me;
5951 if (!me)
return NULL;
5962 if (resolved_location) {
5963 resolved_location[0] = path;
5964 resolved_location[1] = beg_pos_lineno;
5965 resolved_location[2] = beg_pos_column;
5966 resolved_location[3] = end_pos_lineno;
5967 resolved_location[4] = end_pos_column;
5981 me = rb_resolve_me_location(me, 0);
5984 rcount = rb_hash_aref(me2counter, (
VALUE) me);
5992rb_get_coverages(
void)
5994 return GET_VM()->coverages;
5998rb_get_coverage_mode(
void)
6000 return GET_VM()->coverage_mode;
6004rb_set_coverages(
VALUE coverages,
int mode,
VALUE me2counter)
6006 GET_VM()->coverages = coverages;
6007 GET_VM()->me2counter = me2counter;
6008 GET_VM()->coverage_mode = mode;
6012rb_resume_coverages(
void)
6014 int mode = GET_VM()->coverage_mode;
6015 VALUE me2counter = GET_VM()->me2counter;
6016 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);
6017 if (mode & COVERAGE_TARGET_BRANCHES) {
6018 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);
6020 if (mode & COVERAGE_TARGET_METHODS) {
6026rb_suspend_coverages(
void)
6029 if (GET_VM()->coverage_mode & COVERAGE_TARGET_BRANCHES) {
6032 if (GET_VM()->coverage_mode & COVERAGE_TARGET_METHODS) {
6039rb_reset_coverages(
void)
6041 rb_clear_coverages();
6042 rb_iseq_remove_coverage_all();
6043 GET_VM()->coverages =
Qfalse;
6047rb_default_coverage(
int n)
6049 VALUE coverage = rb_ary_hidden_new_fill(3);
6051 int mode = GET_VM()->coverage_mode;
6053 if (mode & COVERAGE_TARGET_LINES) {
6056 RARRAY_ASET(coverage, COVERAGE_INDEX_LINES, lines);
6058 if (mode & COVERAGE_TARGET_BRANCHES) {
6059 branches = rb_ary_hidden_new_fill(2);
6081 VALUE structure = rb_hash_new();
6087 RARRAY_ASET(coverage, COVERAGE_INDEX_BRANCHES, branches);
6093uninterruptible_exit(
VALUE v)
6096 rb_ary_pop(cur_th->pending_interrupt_mask_stack);
6098 cur_th->pending_interrupt_queue_checked = 0;
6099 if (!rb_threadptr_pending_interrupt_empty_p(cur_th)) {
6100 RUBY_VM_SET_INTERRUPT(cur_th->ec);
6108 VALUE interrupt_mask = rb_ident_hash_new();
6111 rb_hash_aset(interrupt_mask, rb_cObject, sym_never);
6113 rb_ary_push(cur_th->pending_interrupt_mask_stack, interrupt_mask);
6117 RUBY_VM_CHECK_INTS(cur_th->ec);
6124 VM_ASSERT(th->specific_storage == NULL);
6126 if (UNLIKELY(specific_key_count > 0)) {
6127 th->specific_storage =
ZALLOC_N(
void *, RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX);
6131rb_internal_thread_specific_key_t
6136 if (specific_key_count == 0 && vm->ractor.cnt > 1) {
6137 rb_raise(
rb_eThreadError,
"The first rb_internal_thread_specific_key_create() is called with multiple ractors");
6139 else if (specific_key_count > RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX) {
6140 rb_raise(
rb_eThreadError,
"rb_internal_thread_specific_key_create() is called more than %d times", RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX);
6143 rb_internal_thread_specific_key_t key = specific_key_count++;
6150 ccan_list_for_each(&cr->threads.set, th, lt_node) {
6151 thread_specific_storage_alloc(th);
6164 VM_ASSERT(rb_thread_ptr(thread_val) == th);
6165 VM_ASSERT(key < RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX);
6166 VM_ASSERT(th->specific_storage);
6168 return th->specific_storage[key];
6177 VM_ASSERT(rb_thread_ptr(thread_val) == th);
6178 VM_ASSERT(key < RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX);
6179 VM_ASSERT(th->specific_storage);
6181 th->specific_storage[key] = data;
6187 struct ccan_list_node node;
6189 rb_interrupt_exec_func_t *func;
6191 enum rb_interrupt_exec_flag flags;
6195rb_threadptr_interrupt_exec_task_mark(
rb_thread_t *th)
6199 ccan_list_for_each(&th->interrupt_exec_tasks, task, node) {
6200 if (task->flags & rb_interrupt_exec_flag_value_data) {
6201 rb_gc_mark((
VALUE)task->data);
6209rb_threadptr_interrupt_exec(
rb_thread_t *th, rb_interrupt_exec_func_t *func,
void *data,
enum rb_interrupt_exec_flag flags)
6221 ccan_list_add_tail(&th->interrupt_exec_tasks, &task->node);
6222 threadptr_set_interrupt_locked(th,
true);
6239 RUBY_DEBUG_LOG(
"task:%p", task);
6242 if (task->flags & rb_interrupt_exec_flag_new_thread) {
6246 (*task->func)(task->data);
6274 rb_interrupt_exec_func_t *func,
void *data,
enum rb_interrupt_exec_flag flags)
6276 RUBY_DEBUG_LOG(
"flags:%d", (
int)flags);
6279 rb_threadptr_interrupt_exec(main_th, func, data, flags | rb_interrupt_exec_flag_new_thread);
#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.
std::atomic< unsigned > rb_atomic_t
Type that is eligible for atomic operations.
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
#define RUBY_INTERNAL_EVENT_SWITCH
Thread switched.
int rb_remove_event_hook(rb_event_hook_func_t func)
Removes the passed function from the list of event hooks.
#define RUBY_EVENT_THREAD_BEGIN
Encountered a new thread.
void(* rb_event_hook_func_t)(rb_event_flag_t evflag, VALUE data, VALUE self, ID mid, VALUE klass)
Type of event hooks.
uint32_t rb_event_flag_t
Represents event(s).
#define RUBY_EVENT_CALL
A method, written in Ruby, is called.
#define RUBY_EVENT_THREAD_END
Encountered an end of a thread.
static void RB_FL_SET_RAW(VALUE obj, VALUE flags)
This is an implementation detail of RB_FL_SET().
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
ID rb_frame_last_func(void)
Returns the ID of the last method in the call stack.
int rb_keyword_given_p(void)
Determines if the current method is given a keyword argument.
int rb_block_given_p(void)
Determines if the current method is given a block.
#define rb_str_new2
Old name of rb_str_new_cstr.
#define ALLOC
Old name of RB_ALLOC.
#define T_STRING
Old name of RUBY_T_STRING.
#define xfree
Old name of ruby_xfree.
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
#define OBJ_FROZEN
Old name of RB_OBJ_FROZEN.
#define xrealloc
Old name of ruby_xrealloc.
#define ID2SYM
Old name of RB_ID2SYM.
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
#define CLASS_OF
Old name of rb_class_of.
#define xmalloc
Old name of ruby_xmalloc.
#define LONG2FIX
Old name of RB_INT2FIX.
#define FIX2INT
Old name of RB_FIX2INT.
#define ZALLOC_N
Old name of RB_ZALLOC_N.
#define T_ICLASS
Old name of RUBY_T_ICLASS.
#define T_HASH
Old name of RUBY_T_HASH.
#define Qtrue
Old name of RUBY_Qtrue.
#define NUM2INT
Old name of RB_NUM2INT.
#define INT2NUM
Old name of RB_INT2NUM.
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define FIX2LONG
Old name of RB_FIX2LONG.
#define T_ARRAY
Old name of RUBY_T_ARRAY.
#define T_OBJECT
Old name of RUBY_T_OBJECT.
#define NIL_P
Old name of RB_NIL_P.
#define POSFIXABLE
Old name of RB_POSFIXABLE.
#define BUILTIN_TYPE
Old name of RB_BUILTIN_TYPE.
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define SYMBOL_P
Old name of RB_SYMBOL_P.
void ruby_stop(int ex)
Calls ruby_cleanup() and exits the process.
#define ruby_debug
This variable controls whether the interpreter is in debug mode.
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
VALUE rb_eSystemExit
SystemExit exception.
VALUE rb_eIOError
IOError exception.
VALUE rb_eStandardError
StandardError exception.
VALUE rb_eTypeError
TypeError exception.
void rb_frozen_error_raise(VALUE frozen_obj, const char *fmt,...)
Raises an instance of rb_eFrozenError.
VALUE rb_eFatal
fatal exception.
VALUE rb_eRuntimeError
RuntimeError exception.
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
VALUE rb_eException
Mother of all exceptions.
VALUE rb_eThreadError
ThreadError exception.
void rb_exit(int status)
Terminates the current execution context.
VALUE rb_eSignal
SignalException exception.
VALUE rb_obj_alloc(VALUE klass)
Allocates an instance of the given class.
VALUE rb_cInteger
Module class.
VALUE rb_obj_hide(VALUE obj)
Make the object invisible from Ruby code.
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
VALUE rb_cThread
Thread class.
VALUE rb_cModule
Module class.
double rb_num2dbl(VALUE num)
Converts an instance of rb_cNumeric into C's double.
VALUE rb_obj_is_kind_of(VALUE obj, VALUE klass)
Queries if the given object is an instance (of possibly descendants) of the given class.
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_dup(VALUE ary)
Duplicates an array.
VALUE rb_ary_delete_at(VALUE ary, long 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_hidden_new(long capa)
Allocates a hidden (no class) empty array.
VALUE rb_ary_clear(VALUE ary)
Destructively removes everything form an array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_ary_entry(VALUE ary, long off)
Queries an element of an array.
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_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 funciton 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.
#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.
void * rb_internal_thread_specific_get(VALUE thread_val, rb_internal_thread_specific_key_t key)
Get thread and tool specific data.
#define RB_NOGVL_INTR_FAIL
Passing this flag to rb_nogvl() prevents it from checking interrupts.
void rb_internal_thread_specific_set(VALUE thread_val, rb_internal_thread_specific_key_t key, void *data)
Set thread and tool specific data.
rb_internal_thread_specific_key_t rb_internal_thread_specific_key_create(void)
Create a key to store thread specific data.
void * rb_nogvl(void *(*func)(void *), void *data1, rb_unblock_function_t *ubf, void *data2, int flags)
Identical to rb_thread_call_without_gvl(), except it additionally takes "flags" that change the behav...
void * rb_thread_call_with_gvl(void *(*func)(void *), void *data1)
(Re-)acquires the GVL.
#define RB_NOGVL_OFFLOAD_SAFE
Passing this flag to rb_nogvl() indicates that the passed function is safe to offload to a background...
void * rb_thread_call_without_gvl2(void *(*func)(void *), void *data1, rb_unblock_function_t *ubf, void *data2)
Identical to rb_thread_call_without_gvl(), except it does not interface with signals etc.
void * rb_thread_call_without_gvl(void *(*func)(void *), void *data1, rb_unblock_function_t *ubf, void *data2)
Allows the passed function to run in parallel with other Ruby threads.
#define RB_BLOCK_CALL_FUNC_ARGLIST(yielded_arg, callback_arg)
Shim for block function parameters.
VALUE rb_yield(VALUE val)
Yields the block.
void rb_throw_obj(VALUE tag, VALUE val)
Identical to rb_throw(), except it allows arbitrary Ruby object to become a tag.
static int rb_fd_max(const rb_fdset_t *f)
It seems this function has no use.
void rb_fd_copy(rb_fdset_t *dst, const fd_set *src, int max)
Destructively overwrites an fdset with another.
void rb_fd_dup(rb_fdset_t *dst, const rb_fdset_t *src)
Identical to rb_fd_copy(), except it copies unlimited number of file descriptors.
void rb_fd_term(rb_fdset_t *f)
Destroys the rb_fdset_t, releasing any memory and resources it used.
static fd_set * rb_fd_ptr(const rb_fdset_t *f)
Raw pointer to fd_set.
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
#define ALLOCA_N(type, n)
#define MEMZERO(p, type, n)
Handy macro to erase a region of memory.
VALUE rb_thread_create(type *q, void *w)
Creates a rb_cThread instance.
void rb_hash_foreach(VALUE q, int_type *w, VALUE e)
Iteration over the given hash.
VALUE rb_ensure(type *q, VALUE w, type *e, VALUE r)
An equivalent of ensure clause.
#define rb_fd_isset
Queries if the given fd is in the rb_fdset_t.
#define rb_fd_select
Waits for multiple file descriptors at once.
#define rb_fd_init
Initialises the :given :rb_fdset_t.
#define rb_fd_set
Sets the given fd to the rb_fdset_t.
#define rb_fd_zero
Clears the given rb_fdset_t.
#define rb_fd_clr
Unsets the given fd from the rb_fdset_t.
#define RARRAY_LEN
Just another name of rb_array_len.
static int RARRAY_LENINT(VALUE ary)
Identical to rb_array_len(), except it differs for the return type.
static void RARRAY_ASET(VALUE ary, long i, VALUE v)
Assigns an object in an array.
#define RARRAY_AREF(a, i)
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
static VALUE RBASIC_CLASS(VALUE obj)
Queries the class of an object.
#define RBASIC(obj)
Convenient casting macro.
#define RCLASS_SUPER
Just another name of rb_class_get_superclass.
#define DATA_PTR(obj)
Convenient getter macro.
#define RHASH_EMPTY_P(h)
Checks if the hash is empty.
#define StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
#define RUBY_TYPED_DEFAULT_FREE
This is a value you can set to rb_data_type_struct::dfree.
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
#define TypedData_Wrap_Struct(klass, data_type, sval)
Converts sval, a pointer to your struct, into a Ruby object.
#define TypedData_Make_Struct(klass, type, data_type, sval)
Identical to TypedData_Wrap_Struct, except it allocates a new data region internally instead of takin...
#define errno
Ractor-aware version of errno.
int ruby_native_thread_p(void)
Queries if the thread which calls this function is a ruby's thread.
int ruby_snprintf(char *str, size_t n, char const *fmt,...)
Our own locale-insensitive version of snprintf(3).
#define RB_PASS_CALLED_KEYWORDS
Pass keywords if current method is called with keywords, useful for argument delegation.
VALUE rb_fiber_scheduler_blocking_operation_wait(VALUE scheduler, void *(*function)(void *), void *data, rb_unblock_function_t *unblock_function, void *data2, int flags, struct rb_fiber_scheduler_blocking_operation_state *state)
Defer the execution of the passed function to the scheduler.
VALUE rb_fiber_scheduler_current(void)
Identical to rb_fiber_scheduler_get(), except it also returns RUBY_Qnil in case of a blocking fiber.
VALUE rb_fiber_scheduler_fiber_interrupt(VALUE scheduler, VALUE fiber, VALUE exception)
Interrupt a fiber by raising an exception.
VALUE rb_fiber_scheduler_block(VALUE scheduler, VALUE blocker, VALUE timeout)
Non-blocking wait for the passed "blocker", which is for instance Thread.join or Mutex....
VALUE rb_fiber_scheduler_set(VALUE scheduler)
Destructively assigns the passed scheduler to that of the current thread that is calling this functio...
VALUE rb_fiber_scheduler_unblock(VALUE scheduler, VALUE blocker, VALUE fiber)
Wakes up a fiber previously blocked using rb_fiber_scheduler_block().
int rb_thread_fd_select(int nfds, rb_fdset_t *rfds, rb_fdset_t *wfds, rb_fdset_t *efds, struct timeval *timeout)
Waits for multiple file descriptors at once.
#define rb_fd_resize(n, f)
Does nothing (defined for compatibility).
static bool RB_TEST(VALUE obj)
Emulates Ruby's "if" statement.
@ RUBY_Qundef
Represents so-called undef.
#define RTEST
This is an old name of RB_TEST.
#define _(args)
This was a transition path from K&R to ANSI.
This is the struct that holds necessary info for a struct.
The data structure which wraps the fd_set bitmap used by select(2).
int maxfd
Maximum allowed number of FDs.
fd_set * fdset
File descriptors buffer.
int capa
Maximum allowed number of FDs.
Ruby's IO, metadata and buffers.
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_mutex_initialize(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_initialize.
void rb_native_mutex_unlock(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_unlock.
void rb_nativethread_lock_unlock(rb_nativethread_lock_t *lock)
Releases a lock.
void rb_native_mutex_destroy(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_destroy.
void rb_nativethread_lock_initialize(rb_nativethread_lock_t *lock)
Fills the passed lock with an initial value.
void rb_nativethread_lock_destroy(rb_nativethread_lock_t *lock)
Destroys the passed mutex.
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
uintptr_t VALUE
Type that represents a Ruby object.
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.