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/coverage.h"
81#include "internal/error.h"
82#include "internal/eval.h"
83#include "internal/gc.h"
84#include "internal/hash.h"
85#include "internal/io.h"
86#include "internal/object.h"
87#include "internal/proc.h"
89#include "internal/signal.h"
90#include "internal/thread.h"
91#include "internal/time.h"
92#include "internal/warnings.h"
100#include "ractor_core.h"
105#include "ccan/list/list.h"
107#ifndef USE_NATIVE_THREAD_PRIORITY
108#define USE_NATIVE_THREAD_PRIORITY 0
109#define RUBY_THREAD_PRIORITY_MAX 3
110#define RUBY_THREAD_PRIORITY_MIN -3
113static VALUE rb_cThreadShield;
114static VALUE cThGroup;
116static VALUE sym_immediate;
117static VALUE sym_on_blocking;
118static VALUE sym_never;
120static uint32_t thread_default_quantum_ms = 100;
122#define THREAD_LOCAL_STORAGE_INITIALISED FL_USER13
123#define THREAD_LOCAL_STORAGE_INITIALISED_P(th) RB_FL_TEST_RAW((th), THREAD_LOCAL_STORAGE_INITIALISED)
126rb_thread_local_storage(
VALUE thread)
128 if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
136 SLEEP_DEADLOCKABLE = 0x01,
137 SLEEP_SPURIOUS_CHECK = 0x02,
138 SLEEP_ALLOW_SPURIOUS = 0x04,
139 SLEEP_NO_CHECKINTS = 0x08,
142static void sleep_forever(
rb_thread_t *th,
unsigned int fl);
143static int sleep_hrtime(
rb_thread_t *, rb_hrtime_t,
unsigned int fl);
145static void rb_thread_sleep_deadly_allow_spurious_wakeup(
VALUE blocker,
VALUE timeout, rb_hrtime_t end);
148static int rb_threadptr_pending_interrupt_empty_p(
const rb_thread_t *th);
149static const char *thread_status_name(
rb_thread_t *th,
int detail);
150static int hrtime_update_expire(rb_hrtime_t *,
const rb_hrtime_t);
151NORETURN(
static void async_bug_fd(
const char *mesg,
int errno_arg,
int fd));
152MAYBE_UNUSED(
static int consume_communication_pipe(
int fd));
155static rb_internal_thread_specific_key_t specific_key_count;
159#define THREAD_SYSTEM_DEPENDENT_IMPLEMENTATION
162 enum rb_thread_status prev_status;
166static void unblock_function_clear(
rb_thread_t *th);
172#define THREAD_BLOCKING_BEGIN(th) do { \
173 struct rb_thread_sched * const sched = TH_SCHED(th); \
174 RB_VM_SAVE_MACHINE_CONTEXT(th); \
175 thread_sched_to_waiting((sched), (th), true);
177#define THREAD_BLOCKING_END(th) \
178 thread_sched_to_running((sched), (th)); \
179 rb_ractor_thread_switch(th->ractor, th, false); \
183#ifdef HAVE_BUILTIN___BUILTIN_CHOOSE_EXPR_CONSTANT_P
184#define only_if_constant(expr, notconst) __builtin_choose_expr(__builtin_constant_p(expr), (expr), (notconst))
186#define only_if_constant(expr, notconst) (__builtin_constant_p(expr) ? (expr) : (notconst))
189#define only_if_constant(expr, notconst) notconst
191#define RB_NOGVL_FAIL_FLAGS (RB_NOGVL_INTR_FAIL | RB_NOGVL_PENDING_INTR_FAIL)
192#define BLOCKING_REGION(th, exec, ubf, ubfarg, flags) do { \
193 struct rb_blocking_region_buffer __region; \
194 if (blocking_region_begin(th, &__region, (ubf), (ubfarg), flags) || \
196 !only_if_constant((flags) & RB_NOGVL_FAIL_FLAGS, TRUE)) { \
199 RB_VM_SAVE_MACHINE_CONTEXT(th); \
200 thread_sched_to_waiting(TH_SCHED(th), th, false); \
202 blocking_region_end(th, &__region); \
210#define RUBY_VM_CHECK_INTS_BLOCKING(ec) vm_check_ints_blocking(ec)
214#ifdef RUBY_ASSERT_CRITICAL_SECTION
215 VM_ASSERT(ruby_assert_critical_section_entered == 0);
220 if (LIKELY(rb_threadptr_pending_interrupt_empty_p(th))) {
221 if (LIKELY(!RUBY_VM_INTERRUPTED_ANY(ec)))
return FALSE;
224 th->pending_interrupt_queue_checked = 0;
225 RUBY_VM_SET_INTERRUPT(ec);
228 int result = rb_threadptr_execute_interrupts(th, 1);
231 if (result || RUBY_VM_INTERRUPTED(ec)) {
233 if (scheduler !=
Qnil) {
244 return vm_check_ints_blocking(ec);
252#if defined(HAVE_POLL)
253# if defined(__linux__)
256# if defined(__FreeBSD_version) && __FreeBSD_version >= 1100000
259# define POLLERR_SET (POLLHUP | POLLERR)
264timeout_prepare(rb_hrtime_t **to, rb_hrtime_t *rel, rb_hrtime_t *end,
268 *rel = rb_timeval2hrtime(timeout);
269 *end = rb_hrtime_add(rb_hrtime_now(), *rel);
277MAYBE_UNUSED(NOINLINE(
static int thread_start_func_2(
rb_thread_t *th,
VALUE *stack_start)));
278MAYBE_UNUSED(
static bool th_has_dedicated_nt(
const rb_thread_t *th));
279MAYBE_UNUSED(
static int waitfd_to_waiting_flag(
int wfd_event));
281#include THREAD_IMPL_SRC
288#ifndef BUSY_WAIT_SIGNALS
289# define BUSY_WAIT_SIGNALS (0)
293# define USE_EVENTFD (0)
296#include "thread_sync.c"
327 if (RUBY_VM_INTERRUPTED_ANY(th->ec)) {
332 RUBY_VM_CHECK_INTS(th->ec);
335 if (!rb_threadptr_pending_interrupt_empty_p(th)) {
341 }
while (!th->ec->raised_flag && RUBY_VM_INTERRUPTED_ANY(th->ec) &&
344 VM_ASSERT(th->unblock.func == NULL);
346 th->unblock.func = func;
347 th->unblock.arg = arg;
357 th->unblock.func = 0;
362threadptr_set_interrupt_locked(
rb_thread_t *th,
bool trap)
366 RUBY_DEBUG_LOG(
"th:%u trap:%d", rb_th_serial(th), trap);
369 RUBY_VM_SET_TRAP_INTERRUPT(th->ec);
372 RUBY_VM_SET_INTERRUPT(th->ec);
375 if (th->unblock.func != NULL) {
376 (th->unblock.func)(th->unblock.arg);
388 threadptr_set_interrupt_locked(th, trap);
397 RUBY_DEBUG_LOG(
"th:%u", rb_th_serial(th));
398 threadptr_set_interrupt(th,
false);
404 threadptr_set_interrupt(th,
true);
412 ccan_list_for_each(&r->threads.set, th, lt_node) {
413 if (th != main_thread) {
414 RUBY_DEBUG_LOG(
"terminate start th:%u status:%s", rb_th_serial(th), thread_status_name(th, TRUE));
416 rb_threadptr_pending_interrupt_enque(th, RUBY_FATAL_THREAD_TERMINATED);
417 rb_threadptr_interrupt(th);
419 RUBY_DEBUG_LOG(
"terminate done th:%u status:%s", rb_th_serial(th), thread_status_name(th, TRUE));
422 RUBY_DEBUG_LOG(
"main thread th:%u", rb_th_serial(th));
430 while (thread->join_list) {
434 thread->join_list = join_list->next;
438 if (target_thread->scheduler !=
Qnil && join_list->fiber) {
442 rb_threadptr_interrupt(target_thread);
444 switch (target_thread->status) {
446 case THREAD_STOPPED_FOREVER:
447 target_thread->status = THREAD_RUNNABLE;
457rb_threadptr_unlock_all_locking_mutexes(
rb_thread_t *th)
459 while (th->keeping_mutexes) {
461 th->keeping_mutexes = mutex->next_mutex;
464 VM_ASSERT(mutex->ec_serial);
465 const char *error_message = rb_mutex_unlock_th(mutex, th, 0);
466 if (error_message) rb_bug(
"invalid keeping_mutexes: %s", error_message);
475 volatile int sleeping = 0;
477 if (cr->threads.main != th) {
478 rb_bug(
"rb_thread_terminate_all: called by child thread (%p, %p)",
479 (
void *)cr->threads.main, (
void *)th);
483 rb_threadptr_unlock_all_locking_mutexes(th);
486 if (EC_EXEC_TAG() == TAG_NONE) {
488 RUBY_DEBUG_LOG(
"th:%u", rb_th_serial(th));
490 terminate_all(cr, th);
492 while (rb_ractor_living_thread_num(cr) > 1) {
493 rb_hrtime_t rel = RB_HRTIME_PER_SEC;
499 native_sleep(th, &rel);
500 RUBY_VM_CHECK_INTS_BLOCKING(ec);
518void rb_threadptr_root_fiber_terminate(
rb_thread_t *th);
519static void threadptr_interrupt_exec_cleanup(
rb_thread_t *th);
522thread_cleanup_func_before_exec(
void *th_ptr)
525 th->status = THREAD_KILLED;
528 th->ec->machine.stack_start = th->ec->machine.stack_end = NULL;
530 threadptr_interrupt_exec_cleanup(th);
531 rb_threadptr_root_fiber_terminate(th);
535thread_cleanup_func(
void *th_ptr,
int atfork)
539 th->locking_mutex =
Qfalse;
540 thread_cleanup_func_before_exec(th_ptr);
543 native_thread_destroy_atfork(th->nt);
561rb_thread_free_native_thread(
void *th_ptr)
565 native_thread_destroy_atfork(th->nt);
573ruby_thread_init_stack(
rb_thread_t *th,
void *local_in_parent_frame)
575 native_thread_init_stack(th, local_in_parent_frame);
579rb_vm_proc_local_ep(
VALUE proc)
581 const VALUE *ep = vm_proc_ep(proc);
584 return rb_vm_ep_local_ep(ep);
593 int argc,
const VALUE *argv,
int kw_splat,
VALUE passed_block_handler,
599 VALUE args = th->invoke_arg.proc.args;
600 const VALUE *args_ptr;
602 VALUE procval = th->invoke_arg.proc.proc;
604 GetProcPtr(procval, proc);
605 const rb_cref_t *cref = rb_proc_refinements_cref_for_call(procval);
607 th->ec->errinfo =
Qnil;
608 th->ec->root_lep = rb_vm_proc_local_ep(procval);
609 th->ec->root_svar =
Qfalse;
611 vm_check_ints_blocking(th->ec);
613 if (th->invoke_type == thread_invoke_type_ractor_proc) {
614 VALUE self = rb_ractor_self(th->ractor);
615 th->thgroup = th->ractor->thgroup_default =
rb_obj_alloc(cThGroup);
620 rb_ractor_receive_parameters(th->ec, th->ractor, args_len, (
VALUE *)args_ptr);
621 vm_check_ints_blocking(th->ec);
623 return rb_vm_invoke_proc_with_self(
626 th->invoke_arg.proc.kw_splat,
627 VM_BLOCK_HANDLER_NONE,
637 th->invoke_arg.proc.args =
Qnil;
643 vm_check_ints_blocking(th->ec);
645 return rb_vm_invoke_proc(
648 th->invoke_arg.proc.kw_splat,
649 VM_BLOCK_HANDLER_NONE,
658 native_set_thread_name(th);
661 switch (th->invoke_type) {
662 case thread_invoke_type_proc:
663 result = thread_do_start_proc(th);
666 case thread_invoke_type_ractor_proc:
667 result = thread_do_start_proc(th);
668 rb_ractor_atexit(th->ec, result);
671 case thread_invoke_type_func:
672 result = (*th->invoke_arg.func.func)(th->invoke_arg.func.arg);
675 case thread_invoke_type_none:
676 rb_bug(
"unreachable");
687 RUBY_DEBUG_LOG(
"th:%u", rb_th_serial(th));
688 VM_ASSERT(th != th->vm->ractor.main_thread);
690 enum ruby_tag_type state;
692 rb_thread_t *ractor_main_th = th->ractor->threads.main;
695 if (rb_ractor_status_p(th->ractor, ractor_blocking)) {
698 rb_vm_ractor_blocking_cnt_dec(th->vm, th->ractor, __FILE__, __LINE__);
711 VM_ASSERT(UNDEF_P(th->value));
713 volatile int fiber_scheduler_closed = 0, event_thread_end_hooked = 0;
718 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
721 result = thread_do_start(th);
724 if (!fiber_scheduler_closed) {
725 fiber_scheduler_closed = 1;
729 if (!event_thread_end_hooked) {
730 event_thread_end_hooked = 1;
734 if (state == TAG_NONE) {
739 errinfo = th->ec->errinfo;
741 VALUE exc = rb_vm_make_jump_tag_but_local_jump(state,
Qundef);
742 if (!
NIL_P(exc)) errinfo = exc;
744 if (state == TAG_FATAL) {
745 if (th->invoke_type == thread_invoke_type_ractor_proc) {
746 rb_ractor_atexit(th->ec,
Qnil);
751 if (th->invoke_type == thread_invoke_type_ractor_proc) {
752 rb_ractor_atexit_exception(th->ec);
758 if (th->report_on_exception) {
759 VALUE mesg = rb_thread_to_s(th->self);
760 rb_str_cat_cstr(mesg,
" terminated with exception (report_on_exception is true):\n");
761 rb_write_error_str(mesg);
762 rb_ec_error_print(th->ec, errinfo);
765 if (th->invoke_type == thread_invoke_type_ractor_proc) {
766 rb_ractor_atexit_exception(th->ec);
769 if (th->vm->thread_abort_on_exception ||
781 VM_ASSERT(!UNDEF_P(th->value));
783 rb_threadptr_join_list_wakeup(th);
784 rb_threadptr_unlock_all_locking_mutexes(th);
786 if (th->invoke_type == thread_invoke_type_ractor_proc) {
787 rb_thread_terminate_all(th);
788 rb_ractor_teardown(th->ec);
791 th->status = THREAD_KILLED;
792 RUBY_DEBUG_LOG(
"killed th:%u", rb_th_serial(th));
794 if (th->vm->ractor.main_thread == th) {
800 rb_threadptr_raise(ractor_main_th, 1, &errinfo);
805 rb_ec_clear_current_thread_trace_func(th->ec);
808 if (th->locking_mutex !=
Qfalse) {
809 rb_bug(
"thread_start_func_2: locking_mutex must not be set (%p:%"PRIxVALUE
")",
810 (
void *)th, th->locking_mutex);
813 if (ractor_main_th->status == THREAD_KILLED &&
814 th->ractor->threads.cnt <= 2 ) {
816 rb_threadptr_interrupt(ractor_main_th);
819 rb_check_deadlock(th->ractor);
821 rb_fiber_close(th->ec->fiber_ptr);
823 thread_cleanup_func(th, FALSE);
824 VM_ASSERT(th->ec->vm_stack == NULL);
829 if (th->invoke_type == thread_invoke_type_ractor_proc) {
830 rb_ractor_postmortem(th, &pf);
833#if defined(USE_MN_THREADS) && USE_MN_THREADS
834 if (th_has_coroutine(th)) {
838 coroutine_thread_terminated(th);
839 rb_ractor_postmortem_free(&pf);
844 if (th->invoke_type == thread_invoke_type_ractor_proc) {
848 thread_sched_to_dead(TH_SCHED(th), th);
849 rb_ractor_living_threads_remove(th->ractor, th);
850 rb_ractor_postmortem_free(&pf);
853 rb_ractor_living_threads_remove(th->ractor, th);
854 thread_sched_to_dead(TH_SCHED(th), th);
861 enum thread_invoke_type type;
874static void thread_specific_storage_alloc(
rb_thread_t *th);
880 rb_thread_t *th = rb_thread_ptr(thval), *current_th = rb_ec_thread_ptr(ec);
883 thread_specific_storage_alloc(th);
887 "can't start a new thread (frozen ThreadGroup)");
893 if (params->type != thread_invoke_type_ractor_proc) {
894 rb_fiber_inherit_storage(ec, th->ec->fiber_ptr);
897 switch (params->type) {
898 case thread_invoke_type_proc:
899 th->invoke_type = thread_invoke_type_proc;
900 th->invoke_arg.proc.args = params->args;
901 th->invoke_arg.proc.proc = params->proc;
905 case thread_invoke_type_ractor_proc:
906 th->invoke_type = thread_invoke_type_ractor_proc;
907 th->ractor = params->g;
908 th->ec->ractor_id = rb_ractor_id(th->ractor);
909 th->ractor->threads.main = th;
910 th->invoke_arg.proc.proc = rb_proc_isolate_bang(params->proc,
Qnil);
915 case thread_invoke_type_func:
916 th->invoke_type = thread_invoke_type_func;
917 th->invoke_arg.func.func = params->fn;
918 th->invoke_arg.func.arg = (
void *)params->args;
922 rb_bug(
"unreachable");
925 th->priority = current_th->priority;
926 th->thgroup = current_th->thgroup;
928 if (th->invoke_type == thread_invoke_type_ractor_proc) {
932 th->pending_interrupt_queue = 0;
933 th->pending_interrupt_mask_stack = 0;
934 th->pending_interrupt_queue_checked = 0;
942 th->pending_interrupt_queue_checked = 0;
943 th->pending_interrupt_mask_stack =
rb_ary_dup(current_th->pending_interrupt_mask_stack);
944 RBASIC_CLEAR_CLASS(th->pending_interrupt_mask_stack);
947 RUBY_DEBUG_LOG(
"r:%u th:%u", rb_ractor_id(th->ractor), rb_th_serial(th));
949 rb_ractor_living_threads_insert(th->ractor, th);
951 if (th->invoke_type == thread_invoke_type_ractor_proc) {
956 enum ruby_tag_type state;
958 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
959 rb_ractor_setup_default_port(params->g);
960 rb_ractor_send_parameters(ec, params->g, params->args);
963 if (state != TAG_NONE) {
964 th->status = THREAD_KILLED;
965 rb_ractor_cancel_creation(params->g, th);
966 EC_JUMP_TAG(ec, state);
971 err = native_thread_create(th);
973 th->status = THREAD_KILLED;
974 if (th->invoke_type == thread_invoke_type_ractor_proc) {
978 rb_ractor_cancel_creation(th->ractor, th);
981 rb_ractor_living_threads_remove(th->ractor, th);
988#define threadptr_initialized(th) ((th)->invoke_type != thread_invoke_type_none)
1011thread_s_new(
int argc,
VALUE *argv,
VALUE klass)
1014 VALUE thread = rb_thread_alloc(klass);
1016 if (GET_RACTOR()->threads.main->status == THREAD_KILLED) {
1021 th = rb_thread_ptr(thread);
1022 if (!threadptr_initialized(th)) {
1023 rb_raise(
rb_eThreadError,
"uninitialized thread - check '%"PRIsVALUE
"#initialize'",
1043 .type = thread_invoke_type_proc,
1047 return thread_create_core(rb_thread_alloc(klass), ¶ms);
1053 if (th->invoke_type == thread_invoke_type_proc) {
1054 return rb_proc_location(th->invoke_arg.proc.proc);
1070 else if (th->invoke_type != thread_invoke_type_none) {
1071 VALUE loc = threadptr_invoke_proc_location(th);
1074 "already initialized thread - %"PRIsVALUE
":%"PRIsVALUE,
1083 .type = thread_invoke_type_proc,
1087 return thread_create_core(thread, ¶ms);
1095 .type = thread_invoke_type_func,
1099 return thread_create_core(rb_thread_alloc(
rb_cThread), ¶ms);
1106 .type = thread_invoke_type_ractor_proc,
1118 const bool multi_objspace = rb_gc_multi_objspace_p();
1119 enum ruby_tag_type alloc_state = TAG_NONE;
1121 void *
const parent_objspace = cr->objspace;
1122 if (multi_objspace) cr->objspace = r->objspace;
1127 VALUE gc_was_disabled = rb_gc_local_disable_no_rest();
1131 if ((alloc_state = EC_EXEC_TAG()) == TAG_NONE) {
1135 if (gc_was_disabled ==
Qfalse) rb_gc_local_enable();
1136 if (multi_objspace) cr->objspace = parent_objspace;
1142 if (alloc_state == TAG_NONE && multi_objspace) {
1144 cr->creating_child_objspace = r->objspace;
1147 if (alloc_state != TAG_NONE) {
1151 rb_gc_objspace_disown(r->objspace);
1155 EC_JUMP_TAG(ec, alloc_state);
1162 enum ruby_tag_type state;
1165 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
1166 thret = thread_create_core(thval, ¶ms);
1169 if (state != TAG_NONE) {
1171 if (cr->creating_child_objspace == r->objspace) {
1172 cr->creating_child_objspace = NULL;
1175 rb_gc_objspace_disown(r->objspace);
1179 EC_JUMP_TAG(ec, state);
1193remove_from_join_list(
VALUE arg)
1198 if (target_thread->status != THREAD_KILLED) {
1201 while (*join_list) {
1202 if (*join_list == p->waiter) {
1203 *join_list = (*join_list)->next;
1207 join_list = &(*join_list)->next;
1217 return th->status == THREAD_KILLED || !UNDEF_P(th->value);
1221thread_join_sleep(
VALUE arg)
1224 rb_thread_t *target_th = p->target, *th = p->waiter->thread;
1225 rb_hrtime_t end = 0, *limit = p->limit;
1228 end = rb_hrtime_add(*limit, rb_hrtime_now());
1231 while (!thread_finished(target_th)) {
1235 if (scheduler !=
Qnil) {
1239 sleep_forever(th, SLEEP_DEADLOCKABLE | SLEEP_ALLOW_SPURIOUS | SLEEP_NO_CHECKINTS);
1243 if (hrtime_update_expire(limit, end)) {
1244 RUBY_DEBUG_LOG(
"timeout target_th:%u", rb_th_serial(target_th));
1248 if (scheduler !=
Qnil) {
1249 VALUE timeout = rb_float_new(hrtime2double(*limit));
1253 th->status = THREAD_STOPPED;
1254 native_sleep(th, limit);
1257 RUBY_VM_CHECK_INTS_BLOCKING(th->ec);
1258 th->status = THREAD_RUNNABLE;
1260 RUBY_DEBUG_LOG(
"interrupted target_th:%u status:%s", rb_th_serial(target_th), thread_status_name(target_th, TRUE));
1273 if (th == target_th) {
1274 rb_raise(
rb_eThreadError,
"Target thread must not be current thread");
1277 if (th->ractor->threads.main == target_th) {
1281 RUBY_DEBUG_LOG(
"target_th:%u status:%s", rb_th_serial(target_th), thread_status_name(target_th, TRUE));
1283 if (target_th->status != THREAD_KILLED) {
1285 waiter.next = target_th->join_list;
1287 waiter.fiber = rb_fiberptr_blocking(fiber) ? NULL : fiber;
1288 target_th->join_list = &waiter;
1291 arg.waiter = &waiter;
1292 arg.target = target_th;
1293 arg.timeout = timeout;
1301 RUBY_DEBUG_LOG(
"success target_th:%u status:%s", rb_th_serial(target_th), thread_status_name(target_th, TRUE));
1303 if (target_th->ec->errinfo !=
Qnil) {
1304 VALUE err = target_th->ec->errinfo;
1309 RUBY_DEBUG_LOG(
"terminated target_th:%u status:%s", rb_th_serial(target_th), thread_status_name(target_th, TRUE));
1314 if (err == RUBY_FATAL_FIBER_KILLED) {
1318 rb_bug(
"thread_join: Fixnum (%d) should not reach here.",
FIX2INT(err));
1321 else if (THROW_DATA_P(target_th->ec->errinfo)) {
1322 rb_bug(
"thread_join: THROW_DATA should not reach here.");
1329 return target_th->self;
1372thread_join_m(
int argc,
VALUE *argv,
VALUE self)
1375 rb_hrtime_t rel = 0, *limit = 0;
1386 if (
NIL_P(timeout)) {
1390 rel = rb_sec2hrtime(NUM2TIMET(timeout));
1394 limit = double2hrtime(&rel,
rb_num2dbl(timeout));
1397 return thread_join(rb_thread_ptr(self), timeout, limit);
1415thread_value(
VALUE self)
1418 thread_join(th,
Qnil, 0);
1419 if (UNDEF_P(th->value)) {
1433#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
1434 if (clock_gettime(CLOCK_MONOTONIC, ts) == 0)
1444NOINLINE(rb_hrtime_t rb_hrtime_now(
void));
1451 return rb_timespec2hrtime(&ts);
1458COMPILER_WARNING_PUSH
1459#if defined(__GNUC__) && __GNUC__ == 7 && __GNUC_MINOR__ <= 3
1460COMPILER_WARNING_IGNORED(-Wmaybe-uninitialized)
1463#define PRIu64 PRI_64_PREFIX "u"
1471hrtime_update_expire(rb_hrtime_t *timeout,
const rb_hrtime_t end)
1473 rb_hrtime_t now = rb_hrtime_now();
1475 if (now > end)
return 1;
1477 RUBY_DEBUG_LOG(
"%"PRIu64
" > %"PRIu64
"", (uint64_t)end, (uint64_t)now);
1479 *timeout = end - now;
1485sleep_hrtime(
rb_thread_t *th, rb_hrtime_t rel,
unsigned int fl)
1487 enum rb_thread_status prev_status = th->status;
1489 rb_hrtime_t end = rb_hrtime_add(rb_hrtime_now(), rel);
1491 th->status = THREAD_STOPPED;
1492 RUBY_VM_CHECK_INTS_BLOCKING(th->ec);
1493 while (th->status == THREAD_STOPPED) {
1494 native_sleep(th, &rel);
1495 woke = vm_check_ints_blocking(th->ec);
1496 if (woke && !(fl & SLEEP_SPURIOUS_CHECK))
1498 if (hrtime_update_expire(&rel, end))
1502 th->status = prev_status;
1507sleep_hrtime_until(
rb_thread_t *th, rb_hrtime_t end,
unsigned int fl)
1509 enum rb_thread_status prev_status = th->status;
1511 rb_hrtime_t rel = rb_hrtime_sub(end, rb_hrtime_now());
1513 th->status = THREAD_STOPPED;
1514 RUBY_VM_CHECK_INTS_BLOCKING(th->ec);
1515 while (th->status == THREAD_STOPPED) {
1516 native_sleep(th, &rel);
1517 woke = vm_check_ints_blocking(th->ec);
1518 if (woke && !(fl & SLEEP_SPURIOUS_CHECK))
1520 if (hrtime_update_expire(&rel, end))
1524 th->status = prev_status;
1531 enum rb_thread_status prev_status = th->status;
1532 enum rb_thread_status status;
1535 status = fl & SLEEP_DEADLOCKABLE ? THREAD_STOPPED_FOREVER : THREAD_STOPPED;
1536 th->status = status;
1538 if (!(fl & SLEEP_NO_CHECKINTS)) RUBY_VM_CHECK_INTS_BLOCKING(th->ec);
1540 while (th->status == status) {
1541 if (fl & SLEEP_DEADLOCKABLE) {
1542 rb_ractor_sleeper_threads_inc(th->ractor);
1543 rb_check_deadlock(th->ractor);
1546 native_sleep(th, 0);
1548 if (fl & SLEEP_DEADLOCKABLE) {
1549 rb_ractor_sleeper_threads_dec(th->ractor);
1551 if (fl & SLEEP_ALLOW_SPURIOUS) {
1555 woke = vm_check_ints_blocking(th->ec);
1557 if (woke && !(fl & SLEEP_SPURIOUS_CHECK)) {
1561 th->status = prev_status;
1567 RUBY_DEBUG_LOG(
"forever");
1568 sleep_forever(GET_THREAD(), SLEEP_SPURIOUS_CHECK);
1574 RUBY_DEBUG_LOG(
"deadly");
1575 sleep_forever(GET_THREAD(), SLEEP_DEADLOCKABLE|SLEEP_SPURIOUS_CHECK);
1579rb_thread_sleep_deadly_allow_spurious_wakeup(
VALUE blocker,
VALUE timeout, rb_hrtime_t end)
1583 if (scheduler !=
Qnil) {
1587 RUBY_DEBUG_LOG(
"...");
1589 sleep_hrtime_until(th, end, SLEEP_SPURIOUS_CHECK);
1592 sleep_forever(th, SLEEP_DEADLOCKABLE);
1602 sleep_hrtime(th, rb_timeval2hrtime(&time), SLEEP_SPURIOUS_CHECK);
1608 RUBY_VM_CHECK_INTS_BLOCKING(ec);
1621 rb_ec_check_ints(GET_EC());
1629rb_thread_check_trap_pending(
void)
1631 return rb_signal_buff_size() != 0;
1638 return (
int)RUBY_VM_INTERRUPTED(rb_thread_ptr(thval)->ec);
1648rb_thread_schedule_limits(uint32_t limits_us)
1652 RUBY_DEBUG_LOG(
"us:%u", (
unsigned int)limits_us);
1654 if (th->running_time_us >= limits_us) {
1655 RUBY_DEBUG_LOG(
"switch %s",
"start");
1657 RB_VM_SAVE_MACHINE_CONTEXT(th);
1658 thread_sched_yield(TH_SCHED(th), th);
1659 rb_ractor_thread_switch(th->ractor, th,
true);
1661 RUBY_DEBUG_LOG(
"switch %s",
"done");
1669 rb_thread_schedule_limits(0);
1670 RUBY_VM_CHECK_INTS(GET_EC());
1679#ifdef RUBY_ASSERT_CRITICAL_SECTION
1680 VM_ASSERT(ruby_assert_critical_section_entered == 0);
1682 VM_ASSERT(th == GET_THREAD());
1684 region->prev_status = th->status;
1685 if (unblock_function_set(th, ubf, arg, flags)) {
1686 th->blocking_region_buffer = region;
1687 th->status = THREAD_STOPPED;
1688 rb_ractor_blocking_threads_inc(th->ractor, __FILE__, __LINE__);
1690 RUBY_DEBUG_LOG(
"thread_id:%p", (
void *)th->nt->thread_id);
1702 unblock_function_clear(th);
1704 unregister_ubf_list(th);
1706 thread_sched_to_running(TH_SCHED(th), th);
1707 rb_ractor_thread_switch(th->ractor, th,
false);
1709 th->blocking_region_buffer = 0;
1710 rb_ractor_blocking_threads_dec(th->ractor, __FILE__, __LINE__);
1711 if (th->status == THREAD_STOPPED) {
1712 th->status = region->prev_status;
1715 RUBY_DEBUG_LOG(
"end");
1719 VM_ASSERT(th == GET_THREAD());
1739 *unblock_function = ubf_select;
1747rb_nogvl(
void *(*func)(
void *),
void *data1,
1756 !rb_threadptr_pending_interrupt_empty_p(th)
1766 if (scheduler !=
Qnil) {
1771 if (!UNDEF_P(result)) {
1772 rb_errno_set(state.saved_errno);
1773 return state.result;
1779 rb_vm_t *vm = rb_ec_vm_ptr(ec);
1780 bool is_main_thread = vm->ractor.main_thread == th;
1781 int saved_errno = 0;
1783 rb_thread_resolve_unblock_function(&ubf, &data2, th);
1785 if (ubf && rb_ractor_living_thread_num(th->ractor) == 1 && is_main_thread) {
1787 vm->ubf_async_safe = 1;
1791 rb_vm_t *
volatile saved_vm = vm;
1792 BLOCKING_REGION(th, {
1794 saved_errno = rb_errno();
1795 }, ubf, data2, flags);
1798 if (is_main_thread) vm->ubf_async_safe = 0;
1801 RUBY_VM_CHECK_INTS_BLOCKING(ec);
1804 rb_errno_set(saved_errno);
1905 return rb_nogvl(func, data1, ubf, data2, 0);
1909waitfd_to_waiting_flag(
int wfd_event)
1911 return wfd_event << 1;
1914static struct ccan_list_head *
1915rb_io_blocking_operations(
struct rb_io *io)
1917 rb_serial_t fork_generation = GET_VM()->fork_gen;
1921 if (io->fork_generation != fork_generation) {
1923 io->fork_generation = fork_generation;
1942 ccan_list_add(rb_io_blocking_operations(io), &blocking_operation->list);
1948 ccan_list_del(&blocking_operation->list);
1957io_blocking_operation_exit(
VALUE _arguments)
1962 rb_io_blocking_operation_pop(arguments->io, blocking_operation);
1966 rb_fiber_t *fiber = io->closing_ec->fiber_ptr;
1968 if (thread->scheduler !=
Qnil) {
1992 VALUE wakeup_mutex = io->wakeup_mutex;
1995 blocking_operation->ec = NULL;
2000 .blocking_operation = blocking_operation
2007 rb_io_blocking_operation_pop(io, blocking_operation);
2012rb_thread_io_blocking_operation_ensure(
VALUE _argument)
2016 rb_io_blocking_operation_exit(arguments->io, arguments->blocking_operation);
2044 rb_io_blocking_operation_enter(io, &blocking_operation);
2048 .blocking_operation = &blocking_operation
2057#if defined(USE_MN_THREADS) && USE_MN_THREADS
2058 return !th_has_dedicated_nt(th) && (events || timeout) && th->blocking;
2064enum io_wait_result {
2072static enum io_wait_result
2073thread_io_wait_events(
rb_thread_t *th,
int fd,
int events,
const struct timeval *timeout,
2074 bool known_not_ready)
2076#if defined(USE_MN_THREADS) && USE_MN_THREADS
2077 if (thread_io_mn_schedulable(th, events, timeout)) {
2078 rb_hrtime_t rel, *prel;
2081 rel = rb_timeval2hrtime(timeout);
2088 VM_ASSERT(prel || (events & (RB_WAITFD_IN | RB_WAITFD_OUT)));
2090 enum thread_sched_waiting_flag flags = waitfd_to_waiting_flag(events);
2091 if (known_not_ready) flags |= thread_sched_waiting_io_force;
2093 switch (thread_sched_wait_events(TH_SCHED(th), th, fd, flags, prel)) {
2094 case thread_sched_wait_event:
2095 return io_wait_ready;
2096 case thread_sched_wait_timeout:
2098 return io_wait_unhandled;
2099 case thread_sched_wait_unavailable:
2102 return io_wait_unhandled;
2106 return io_wait_unhandled;
2111blocking_call_retryable_p(
int r,
int eno)
2113 if (r != -1)
return false;
2117#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
2127rb_thread_mn_schedulable(
VALUE thval)
2130 return th->mn_schedulable;
2134rb_thread_io_blocking_call(
struct rb_io* io, rb_blocking_function_t *func,
void *data1,
int events)
2139 RUBY_DEBUG_LOG(
"th:%u fd:%d ev:%d", rb_th_serial(th), io->
fd, events);
2142 volatile int saved_errno = 0;
2143 enum ruby_tag_type state;
2144 volatile bool prev_mn_schedulable = th->mn_schedulable;
2145 th->mn_schedulable = thread_io_mn_schedulable(th, events, NULL);
2158 rb_io_blocking_operation_enter(io, &blocking_operation);
2162 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
2163 volatile enum ruby_tag_type saved_state = state;
2165 BLOCKING_REGION(th, {
2167 saved_errno =
errno;
2168 }, ubf_select, th, FALSE);
2171 if (events && blocking_call_retryable_p((
int)val, saved_errno)) {
2173 if (thread_io_wait_events(th, fd, events, NULL,
true) == io_wait_ready) {
2174 RUBY_VM_CHECK_INTS_BLOCKING(ec);
2177 else if (th->mn_schedulable) {
2180 rb_thread_wait_for_single_fd(th, fd, events, NULL);
2181 RUBY_VM_CHECK_INTS_BLOCKING(ec);
2186 RUBY_VM_CHECK_INTS_BLOCKING(ec);
2188 state = saved_state;
2192 th = rb_ec_thread_ptr(ec);
2193 th->mn_schedulable = prev_mn_schedulable;
2196 rb_io_blocking_operation_exit(io, &blocking_operation);
2199 EC_JUMP_TAG(ec, state);
2203 if (saved_errno == ETIMEDOUT) {
2207 errno = saved_errno;
2213rb_thread_io_blocking_region(
struct rb_io *io, rb_blocking_function_t *func,
void *data1)
2215 return rb_thread_io_blocking_call(io, func, data1, 0);
2263 fprintf(stderr,
"[BUG] rb_thread_call_with_gvl() is called by non-ruby thread\n");
2268 prev_unblock = th->unblock;
2272 return (*func)(data1);
2275 blocking_region_end(th, brb);
2279 int released = blocking_region_begin(th, brb, prev_unblock.func, prev_unblock.arg, FALSE);
2281 RB_VM_SAVE_MACHINE_CONTEXT(th);
2282 thread_sched_to_waiting(TH_SCHED(th), th,
true);
2291ruby_thread_has_gvl_p(
void)
2295 if (th && th->blocking_region_buffer == 0) {
2312thread_s_pass(
VALUE klass)
2337rb_threadptr_pending_interrupt_clear(
rb_thread_t *th)
2346 th->pending_interrupt_queue_checked = 0;
2350threadptr_check_pending_interrupt_queue(
rb_thread_t *th)
2352 if (!th->pending_interrupt_queue) {
2357enum handle_interrupt_timing {
2359 INTERRUPT_IMMEDIATE,
2360 INTERRUPT_ON_BLOCKING,
2364static enum handle_interrupt_timing
2367 if (sym == sym_immediate) {
2368 return INTERRUPT_IMMEDIATE;
2370 else if (sym == sym_on_blocking) {
2371 return INTERRUPT_ON_BLOCKING;
2373 else if (sym == sym_never) {
2374 return INTERRUPT_NEVER;
2381static enum handle_interrupt_timing
2385 long mask_stack_len =
RARRAY_LEN(th->pending_interrupt_mask_stack);
2390 for (i=0; i<mask_stack_len; i++) {
2391 mask = mask_stack[mask_stack_len-(i+1)];
2396 return rb_threadptr_pending_interrupt_from_symbol(th, mask);
2408 klass =
RBASIC(mod)->klass;
2410 else if (mod != RCLASS_ORIGIN(mod)) {
2414 if ((sym = rb_hash_aref(mask, klass)) !=
Qnil) {
2415 return rb_threadptr_pending_interrupt_from_symbol(th, sym);
2420 return INTERRUPT_NONE;
2424rb_threadptr_pending_interrupt_empty_p(
const rb_thread_t *th)
2426 return RARRAY_LEN(th->pending_interrupt_queue) == 0;
2433 for (i=0; i<
RARRAY_LEN(th->pending_interrupt_queue); i++) {
2443rb_threadptr_pending_interrupt_deque(
rb_thread_t *th,
enum handle_interrupt_timing timing)
2448 for (i=0; i<
RARRAY_LEN(th->pending_interrupt_queue); i++) {
2451 enum handle_interrupt_timing mask_timing = rb_threadptr_pending_interrupt_check_mask(th,
CLASS_OF(err));
2453 switch (mask_timing) {
2454 case INTERRUPT_ON_BLOCKING:
2455 if (timing != INTERRUPT_ON_BLOCKING) {
2459 case INTERRUPT_NONE:
2460 case INTERRUPT_IMMEDIATE:
2463 case INTERRUPT_NEVER:
2468 th->pending_interrupt_queue_checked = 1;
2472 if (rb_threadptr_pending_interrupt_empty_p(th)) {
2473 th->pending_interrupt_queue_checked = 1;
2480threadptr_pending_interrupt_active_p(
rb_thread_t *th)
2487 if (th->pending_interrupt_queue_checked) {
2491 if (rb_threadptr_pending_interrupt_empty_p(th)) {
2503 if (val != sym_immediate && val != sym_on_blocking && val != sym_never) {
2504 rb_raise(rb_eArgError,
"unknown mask signature");
2512 if (
RTEST(*maskp)) {
2514 VALUE prev = *maskp;
2515 *maskp = rb_ident_hash_new();
2520 rb_hash_aset(*maskp, key, val);
2614rb_thread_s_handle_interrupt(
VALUE self,
VALUE mask_arg)
2620 enum ruby_tag_type state;
2623 rb_raise(rb_eArgError,
"block is needed.");
2626 mask_arg = rb_to_hash_type(mask_arg);
2628 if (
OBJ_FROZEN(mask_arg) && rb_hash_compare_by_id_p(mask_arg)) {
2634 if (UNDEF_P(mask)) {
2645 rb_ary_push(th->pending_interrupt_mask_stack, mask);
2646 if (!rb_threadptr_pending_interrupt_empty_p(th)) {
2647 th->pending_interrupt_queue_checked = 0;
2648 RUBY_VM_SET_INTERRUPT(th->ec);
2651 EC_PUSH_TAG(th->ec);
2652 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
2657 rb_ary_pop(th->pending_interrupt_mask_stack);
2658 if (!rb_threadptr_pending_interrupt_empty_p(th)) {
2659 th->pending_interrupt_queue_checked = 0;
2660 RUBY_VM_SET_INTERRUPT(th->ec);
2663 RUBY_VM_CHECK_INTS(th->ec);
2666 EC_JUMP_TAG(th->ec, state);
2683rb_thread_pending_interrupt_p(
int argc,
VALUE *argv,
VALUE target_thread)
2685 rb_thread_t *target_th = rb_thread_ptr(target_thread);
2687 if (!target_th->pending_interrupt_queue) {
2690 if (rb_threadptr_pending_interrupt_empty_p(target_th)) {
2694 VALUE err = argv[0];
2696 rb_raise(
rb_eTypeError,
"class or module required for rescue clause");
2698 return RBOOL(rb_threadptr_pending_interrupt_include_p(target_th, err));
2763rb_thread_s_pending_interrupt_p(
int argc,
VALUE *argv,
VALUE self)
2765 return rb_thread_pending_interrupt_p(argc, argv, GET_THREAD()->self);
2768NORETURN(
static void rb_threadptr_to_kill(
rb_thread_t *th));
2773 VM_ASSERT(GET_THREAD() == th);
2774 rb_threadptr_pending_interrupt_clear(th);
2775 th->status = THREAD_RUNNABLE;
2777 th->ec->errinfo =
INT2FIX(TAG_FATAL);
2778 EC_JUMP_TAG(th->ec, TAG_FATAL);
2788 old = ATOMIC_LOAD_RELAXED(ec->interrupt_flag);
2791 old = ATOMIC_CAS(ec->interrupt_flag, interrupt, interrupt & ec->interrupt_mask);
2792 }
while (old != interrupt);
2793 return interrupt & (
rb_atomic_t)~ec->interrupt_mask;
2796static void threadptr_interrupt_exec_exec(
rb_thread_t *th);
2804rb_threadptr_execute_interrupts(
rb_thread_t *th,
int blocking_timing)
2807 int postponed_job_interrupt = 0;
2810 VM_ASSERT(GET_THREAD() == th);
2812 if (th->ec->raised_flag)
return ret;
2814 while ((interrupt = threadptr_get_interrupts(th)) != 0) {
2816 int timer_interrupt;
2817 int pending_interrupt;
2819 int terminate_interrupt;
2821 timer_interrupt = interrupt & TIMER_INTERRUPT_MASK;
2822 pending_interrupt = interrupt & PENDING_INTERRUPT_MASK;
2823 postponed_job_interrupt = interrupt & POSTPONED_JOB_INTERRUPT_MASK;
2824 trap_interrupt = interrupt & TRAP_INTERRUPT_MASK;
2825 terminate_interrupt = interrupt & TERMINATE_INTERRUPT_MASK;
2827 if (interrupt & VM_BARRIER_INTERRUPT_MASK) {
2831 if (postponed_job_interrupt) {
2832 rb_postponed_job_flush(th->vm);
2835 if (trap_interrupt) {
2837 if (th == th->vm->ractor.main_thread) {
2838 enum rb_thread_status prev_status = th->status;
2840 th->status = THREAD_RUNNABLE;
2842 while ((sig = rb_get_next_signal()) != 0) {
2843 ret |= rb_signal_exec(th, sig);
2846 th->status = prev_status;
2849 if (!ccan_list_empty(&th->interrupt_exec_tasks)) {
2850 enum rb_thread_status prev_status = th->status;
2852 th->status = THREAD_RUNNABLE;
2854 threadptr_interrupt_exec_exec(th);
2856 th->status = prev_status;
2861 if (pending_interrupt && threadptr_pending_interrupt_active_p(th)) {
2862 VALUE err = rb_threadptr_pending_interrupt_deque(th, blocking_timing ? INTERRUPT_ON_BLOCKING : INTERRUPT_NONE);
2863 RUBY_DEBUG_LOG(
"err:%"PRIdVALUE, err);
2869 else if (err == RUBY_FATAL_THREAD_KILLED ||
2870 err == RUBY_FATAL_THREAD_TERMINATED ||
2872 terminate_interrupt = 1;
2875 if (err == th->vm->special_exceptions[ruby_error_stream_closed]) {
2877 err = ruby_vm_special_exception_copy(err);
2880 if (th->status == THREAD_STOPPED ||
2881 th->status == THREAD_STOPPED_FOREVER)
2882 th->status = THREAD_RUNNABLE;
2887 if (terminate_interrupt) {
2888 rb_threadptr_to_kill(th);
2891 if (timer_interrupt) {
2892 uint32_t limits_us = thread_default_quantum_ms * 1000;
2894 if (th->priority > 0)
2895 limits_us <<= th->priority;
2897 limits_us >>= -th->priority;
2899 if (th->status == THREAD_RUNNABLE)
2900 th->running_time_us += 10 * 1000;
2902 VM_ASSERT(th->ec->cfp);
2906 rb_thread_schedule_limits(limits_us);
2913rb_thread_execute_interrupts(
VALUE thval)
2915 rb_threadptr_execute_interrupts(rb_thread_ptr(thval), 1);
2921 rb_threadptr_interrupt(th);
2929 if (rb_threadptr_dead(target_th)) {
2937 exc = rb_make_exception(argc, argv);
2942 if (rb_threadptr_dead(target_th)) {
2946 rb_ec_setup_exception(GET_EC(), exc,
Qundef);
2947 rb_threadptr_pending_interrupt_enque(target_th, exc);
2948 rb_threadptr_interrupt(target_th);
2954rb_threadptr_signal_raise(
rb_thread_t *th,
int sig)
2960 rb_threadptr_raise(th->vm->ractor.main_thread, 2, argv);
2966 rb_thread_t *target_th = th->vm->ractor.main_thread;
2968 if (rb_threadptr_dead(target_th)) {
2977 if (rb_threadptr_dead(target_th)) {
2981 rb_ec_setup_exception(GET_EC(), exc,
Qundef);
2982 rb_threadptr_pending_interrupt_enque(target_th, exc);
2983 rb_threadptr_interrupt(target_th);
2995 rb_threadptr_raise(th->vm->ractor.main_thread, 2, argv);
3001 if (ec->raised_flag & RAISED_EXCEPTION) {
3004 ec->raised_flag |= RAISED_EXCEPTION;
3011 if (!(ec->raised_flag & RAISED_EXCEPTION)) {
3014 ec->raised_flag &= ~RAISED_EXCEPTION;
3039thread_io_close_notify_all(
VALUE _io)
3044 rb_vm_t *vm = io->closing_ec->thread_ptr->vm;
3045 VALUE error = vm->special_exceptions[ruby_error_stream_closed];
3048 ccan_list_for_each(rb_io_blocking_operations(io), blocking_operation, list) {
3056 if (thread->scheduler !=
Qnil) {
3062 rb_threadptr_pending_interrupt_enque(thread, error);
3063 rb_threadptr_interrupt(thread);
3070 return (
VALUE)count;
3074rb_thread_io_close_interrupt(
struct rb_io *io)
3077 if (io->closing_ec) {
3082 if (ccan_list_empty(rb_io_blocking_operations(io))) {
3088 io->closing_ec = ec;
3092 rb_mutex_allow_trap(io->wakeup_mutex, 1);
3097 return (
size_t)result;
3101rb_thread_io_close_wait(
struct rb_io* io)
3103 VALUE wakeup_mutex = io->wakeup_mutex;
3111 while (!ccan_list_empty(rb_io_blocking_operations(io))) {
3117 io->wakeup_mutex =
Qnil;
3118 io->closing_ec = NULL;
3124 rb_warn(
"rb_thread_fd_close is deprecated (and is now a no-op).");
3148thread_raise_m(
int argc,
VALUE *argv,
VALUE self)
3153 threadptr_check_pending_interrupt_queue(target_th);
3155 if (rb_threadptr_dead(target_th)) {
3159 VALUE exception = rb_exception_setup(argc, argv);
3160 rb_threadptr_pending_interrupt_enque(target_th, exception);
3161 rb_threadptr_interrupt(target_th);
3164 if (current_th == target_th) {
3165 RUBY_VM_CHECK_INTS(target_th->ec);
3190 if (target_th->to_kill || target_th->status == THREAD_KILLED) {
3193 if (target_th == target_th->vm->ractor.main_thread) {
3197 RUBY_DEBUG_LOG(
"target_th:%u", rb_th_serial(target_th));
3199 if (target_th == GET_THREAD()) {
3201 rb_threadptr_to_kill(target_th);
3204 threadptr_check_pending_interrupt_queue(target_th);
3205 rb_threadptr_pending_interrupt_enque(target_th, RUBY_FATAL_THREAD_KILLED);
3206 rb_threadptr_interrupt(target_th);
3213rb_thread_to_be_killed(
VALUE thread)
3217 if (target_th->to_kill || target_th->status == THREAD_KILLED) {
3293 if (target_th->status == THREAD_KILLED)
return Qnil;
3295 rb_threadptr_ready(target_th);
3297 if (target_th->status == THREAD_STOPPED ||
3298 target_th->status == THREAD_STOPPED_FOREVER) {
3299 target_th->status = THREAD_RUNNABLE;
3341 "stopping only thread\n\tnote: use sleep to stop forever");
3374 return rb_ractor_thread_list();
3400 return rb_thread_list();
3406 return GET_THREAD()->self;
3419thread_s_current(
VALUE klass)
3427 return GET_RACTOR()->threads.main->self;
3438rb_thread_s_main(
VALUE klass)
3465rb_thread_s_abort_exc(
VALUE _)
3467 return RBOOL(GET_THREAD()->vm->thread_abort_on_exception);
3502rb_thread_s_abort_exc_set(
VALUE self,
VALUE val)
3504 GET_THREAD()->vm->thread_abort_on_exception =
RTEST(val);
3525rb_thread_abort_exc(
VALUE thread)
3527 return RBOOL(rb_thread_ptr(thread)->abort_on_exception);
3545rb_thread_abort_exc_set(
VALUE thread,
VALUE val)
3547 rb_thread_ptr(thread)->abort_on_exception =
RTEST(val);
3595rb_thread_s_report_exc(
VALUE _)
3597 return RBOOL(GET_THREAD()->vm->thread_report_on_exception);
3632rb_thread_s_report_exc_set(
VALUE self,
VALUE val)
3634 GET_THREAD()->vm->thread_report_on_exception =
RTEST(val);
3651rb_thread_s_ignore_deadlock(
VALUE _)
3653 return RBOOL(GET_THREAD()->vm->thread_ignore_deadlock);
3678rb_thread_s_ignore_deadlock_set(
VALUE self,
VALUE val)
3680 GET_THREAD()->vm->thread_ignore_deadlock =
RTEST(val);
3702rb_thread_report_exc(
VALUE thread)
3704 return RBOOL(rb_thread_ptr(thread)->report_on_exception);
3722rb_thread_report_exc_set(
VALUE thread,
VALUE val)
3724 rb_thread_ptr(thread)->report_on_exception =
RTEST(val);
3739rb_thread_group(
VALUE thread)
3741 return rb_thread_ptr(thread)->thgroup;
3747 switch (th->status) {
3748 case THREAD_RUNNABLE:
3749 return th->to_kill ?
"aborting" :
"run";
3750 case THREAD_STOPPED_FOREVER:
3751 if (detail)
return "sleep_forever";
3752 case THREAD_STOPPED:
3764 return th->status == THREAD_KILLED;
3800rb_thread_status(
VALUE thread)
3804 if (rb_threadptr_dead(target_th)) {
3805 if (!
NIL_P(target_th->ec->errinfo) &&
3806 !
FIXNUM_P(target_th->ec->errinfo)) {
3814 return rb_str_new2(thread_status_name(target_th, FALSE));
3834rb_thread_alive_p(
VALUE thread)
3836 return RBOOL(!thread_finished(rb_thread_ptr(thread)));
3854rb_thread_stop_p(
VALUE thread)
3858 if (rb_threadptr_dead(th)) {
3861 return RBOOL(th->status == THREAD_STOPPED || th->status == THREAD_STOPPED_FOREVER);
3872rb_thread_getname(
VALUE thread)
3874 return rb_thread_ptr(thread)->name;
3893 enc = rb_enc_get(name);
3894 if (!rb_enc_asciicompat(enc)) {
3895 rb_raise(rb_eArgError,
"ASCII incompatible encoding (%s)",
3900 target_th->name = name;
3901 if (threadptr_initialized(target_th) && target_th->has_dedicated_nt) {
3902 native_set_another_thread_name(target_th->nt->thread_id, name);
3907#if USE_NATIVE_THREAD_NATIVE_THREAD_ID
3931rb_thread_native_thread_id(
VALUE thread)
3934 if (rb_threadptr_dead(target_th))
return Qnil;
3935 return native_thread_native_thread_id(target_th);
3938# define rb_thread_native_thread_id rb_f_notimplement
3949rb_thread_to_s(
VALUE thread)
3956 status = thread_status_name(target_th, TRUE);
3957 str = rb_sprintf(
"#<%"PRIsVALUE
":%p", cname, (
void *)thread);
3958 if (!
NIL_P(target_th->name)) {
3959 rb_str_catf(str,
"@%"PRIsVALUE, target_th->name);
3961 if ((loc = threadptr_invoke_proc_location(target_th)) !=
Qnil) {
3962 rb_str_catf(str,
" %"PRIsVALUE
":%"PRIsVALUE,
3965 rb_str_catf(str,
" %s>", status);
3971#define recursive_key id__recursive_key__
3976 if (
id == recursive_key) {
3977 return th->ec->local_storage_recursive_hash;
3981 struct rb_id_table *local_storage = th->ec->local_storage;
3983 if (local_storage != NULL && rb_id_table_lookup(local_storage,
id, &val)) {
3995 return threadptr_local_aref(rb_thread_ptr(thread),
id);
4062 if (!
id)
return Qnil;
4080rb_thread_fetch(
int argc,
VALUE *argv,
VALUE self)
4091 if (block_given && argc == 2) {
4092 rb_warn(
"block supersedes default value argument");
4097 if (
id == recursive_key) {
4098 return target_th->ec->local_storage_recursive_hash;
4100 else if (
id && target_th->ec->local_storage &&
4101 rb_id_table_lookup(target_th->ec->local_storage,
id, &val)) {
4104 else if (block_given) {
4107 else if (argc == 1) {
4108 rb_key_err_raise(rb_sprintf(
"key not found: %+"PRIsVALUE, key), self, key);
4118 if (
id == recursive_key) {
4119 th->ec->local_storage_recursive_hash = val;
4123 struct rb_id_table *local_storage = th->ec->local_storage;
4126 if (!local_storage)
return Qnil;
4127 rb_id_table_delete(local_storage,
id);
4131 if (local_storage == NULL) {
4132 th->ec->local_storage = local_storage = rb_id_table_create(0);
4134 rb_id_table_insert(local_storage,
id, val);
4147 return threadptr_local_aset(rb_thread_ptr(thread),
id, val);
4198rb_thread_variable_get(
VALUE thread,
VALUE key)
4203 if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
4206 locals = rb_thread_local_storage(thread);
4207 return rb_hash_aref(locals, symbol);
4228 locals = rb_thread_local_storage(thread);
4250 struct rb_id_table *local_storage = rb_thread_ptr(self)->ec->local_storage;
4252 if (!
id || local_storage == NULL) {
4255 return RBOOL(rb_id_table_lookup(local_storage,
id, &val));
4258static enum rb_id_table_iterator_result
4259thread_keys_i(
ID key,
VALUE value,
void *ary)
4262 return ID_TABLE_CONTINUE;
4269 return rb_ractor_living_thread_num(GET_RACTOR()) == 1;
4287rb_thread_keys(
VALUE self)
4289 struct rb_id_table *local_storage = rb_thread_ptr(self)->ec->local_storage;
4292 if (local_storage) {
4293 rb_id_table_foreach(local_storage, thread_keys_i, (
void *)ary);
4323rb_thread_variables(
VALUE thread)
4329 if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
4332 locals = rb_thread_local_storage(thread);
4360 if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
4363 locals = rb_thread_local_storage(thread);
4365 return RBOOL(rb_hash_lookup(locals, symbol) !=
Qnil);
4384rb_thread_priority(
VALUE thread)
4386 return INT2NUM(rb_thread_ptr(thread)->priority);
4417rb_thread_priority_set(
VALUE thread,
VALUE prio)
4422#if USE_NATIVE_THREAD_PRIORITY
4423 target_th->priority =
NUM2INT(prio);
4424 native_thread_apply_priority(th);
4427 if (priority > RUBY_THREAD_PRIORITY_MAX) {
4428 priority = RUBY_THREAD_PRIORITY_MAX;
4430 else if (priority < RUBY_THREAD_PRIORITY_MIN) {
4431 priority = RUBY_THREAD_PRIORITY_MIN;
4433 target_th->priority = (int8_t)priority;
4435 return INT2NUM(target_th->priority);
4440#if defined(NFDBITS) && defined(HAVE_RB_FD_INIT)
4476 FD_ZERO(fds->
fdset);
4480fdset_memsize(
int maxfd)
4482 size_t o = howmany(maxfd, NFDBITS) *
sizeof(fd_mask);
4483 if (o <
sizeof(fd_set)) {
4484 return sizeof(fd_set);
4492 size_t size = fdset_memsize(
rb_fd_max(src));
4501 ruby_xfree_sized(fds->
fdset, fdset_memsize(fds->
maxfd));
4516 size_t m = fdset_memsize(n + 1);
4517 size_t o = fdset_memsize(fds->
maxfd);
4520 fds->
fdset = ruby_xrealloc_sized(fds->
fdset, m, o);
4521 memset((
char *)fds->
fdset + o, 0, m - o);
4530 FD_SET(n, fds->
fdset);
4536 if (n >= fds->
maxfd)
return;
4537 FD_CLR(n, fds->
fdset);
4543 if (n >= fds->
maxfd)
return 0;
4544 return FD_ISSET(n, fds->
fdset) != 0;
4550 size_t size = fdset_memsize(max);
4551 dst->
fdset = ruby_xrealloc_sized(dst->
fdset, size, fdset_memsize(dst->
maxfd));
4553 memcpy(dst->
fdset, src, size);
4559 size_t size = fdset_memsize(
rb_fd_max(src));
4560 dst->
fdset = ruby_xrealloc_sized(dst->
fdset, size, fdset_memsize(dst->
maxfd));
4568 fd_set *r = NULL, *w = NULL, *e = NULL;
4581 return select(n, r, w, e, timeout);
4584#define rb_fd_no_init(fds) ((void)((fds)->fdset = 0), (void)((fds)->maxfd = 0))
4591#define FD_ZERO(f) rb_fd_zero(f)
4592#define FD_SET(i, f) rb_fd_set((i), (f))
4593#define FD_CLR(i, f) rb_fd_clr((i), (f))
4594#define FD_ISSET(i, f) rb_fd_isset((i), (f))
4596#elif defined(_WIN32)
4601 set->
capa = FD_SETSIZE;
4603 FD_ZERO(set->
fdset);
4614fdset_memsize(
int capa)
4616 if (
capa == FD_SETSIZE) {
4617 return sizeof(fd_set);
4619 return sizeof(
unsigned int) + (
capa *
sizeof(SOCKET));
4625 ruby_xfree_sized(set->
fdset, fdset_memsize(set->
capa));
4634 SOCKET s = rb_w32_get_osfhandle(fd);
4636 for (i = 0; i < set->
fdset->fd_count; i++) {
4637 if (set->
fdset->fd_array[i] == s) {
4641 if (set->
fdset->fd_count >= (
unsigned)set->
capa) {
4642 set->
capa = (set->
fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
4644 rb_xrealloc_mul_add(
4645 set->
fdset, set->
capa,
sizeof(SOCKET),
sizeof(
unsigned int));
4647 set->
fdset->fd_array[set->
fdset->fd_count++] = s;
4655#define FD_ZERO(f) rb_fd_zero(f)
4656#define FD_SET(i, f) rb_fd_set((i), (f))
4657#define FD_CLR(i, f) rb_fd_clr((i), (f))
4658#define FD_ISSET(i, f) rb_fd_isset((i), (f))
4660#define rb_fd_no_init(fds) (void)((fds)->fdset = 0)
4664#ifndef rb_fd_no_init
4665#define rb_fd_no_init(fds) (void)(fds)
4669wait_retryable(
volatile int *result,
int errnum, rb_hrtime_t *rel, rb_hrtime_t end)
4679 if (rel && hrtime_update_expire(rel, end)) {
4689 return !hrtime_update_expire(rel, end);
4709select_set_free(
VALUE p)
4724 volatile int result = 0;
4726 rb_hrtime_t *to, rel, end = 0;
4728 timeout_prepare(&to, &rel, &end, set->timeout);
4729 volatile rb_hrtime_t endtime = end;
4730#define restore_fdset(dst, src) \
4731 ((dst) ? rb_fd_dup(dst, src) : (void)0)
4732#define do_select_update() \
4733 (restore_fdset(set->rset, &set->orig_rset), \
4734 restore_fdset(set->wset, &set->orig_wset), \
4735 restore_fdset(set->eset, &set->orig_eset), \
4741 BLOCKING_REGION(set->th, {
4744 if (!RUBY_VM_INTERRUPTED(set->th->ec)) {
4745 result = native_fd_select(set->max,
4746 set->rset, set->wset, set->eset,
4747 rb_hrtime2timeval(&tv, to), set->th);
4748 if (result < 0) lerrno = errno;
4750 }, ubf_select, set->th, TRUE);
4752 RUBY_VM_CHECK_INTS_BLOCKING(set->th->ec);
4753 }
while (wait_retryable(&result, lerrno, to, endtime) && do_select_update());
4755 RUBY_VM_CHECK_INTS_BLOCKING(set->th->ec);
4761 return (
VALUE)result;
4770 set.th = GET_THREAD();
4771 RUBY_VM_CHECK_INTS_BLOCKING(set.th->ec);
4776 set.timeout = timeout;
4778 if (!set.rset && !set.wset && !set.eset) {
4787#define fd_init_copy(f) do { \
4789 rb_fd_resize(set.max - 1, set.f); \
4790 if (&set.orig_##f != set.f) { \
4791 rb_fd_init_copy(&set.orig_##f, set.f); \
4795 rb_fd_no_init(&set.orig_##f); \
4809#define POLLIN_SET (POLLRDNORM | POLLRDBAND | POLLIN | POLLHUP | POLLERR)
4810#define POLLOUT_SET (POLLWRBAND | POLLWRNORM | POLLOUT | POLLERR)
4811#define POLLEX_SET (POLLPRI)
4814# define POLLERR_SET (0)
4818wait_for_single_fd_blocking_region(
rb_thread_t *th,
struct pollfd *fds, nfds_t nfds,
4819 rb_hrtime_t *
const to,
volatile int *lerrno)
4822 volatile int result = 0;
4825 BLOCKING_REGION(th, {
4826 if (!RUBY_VM_INTERRUPTED(th->ec)) {
4827 result = ppoll(fds, nfds, rb_hrtime2timespec(&ts, to), 0);
4828 if (result < 0) *lerrno = errno;
4830 }, ubf_select, th, TRUE);
4840 struct pollfd fds[1] = {{
4842 .events = (short)events,
4845 volatile int result = 0;
4848 enum ruby_tag_type state;
4849 volatile int lerrno;
4855 blocking_operation.ec = ec;
4856 rb_io_blocking_operation_enter(io, &blocking_operation);
4859 if (timeout == NULL && thread_io_wait_events(th, fd, events, NULL,
false) == io_wait_ready) {
4862 fds[0].revents = events;
4867 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
4868 rb_hrtime_t *to, rel, end = 0;
4869 RUBY_VM_CHECK_INTS_BLOCKING(ec);
4870 timeout_prepare(&to, &rel, &end, timeout);
4872 nfds = numberof(fds);
4873 result = wait_for_single_fd_blocking_region(th, fds, nfds, to, &lerrno);
4875 RUBY_VM_CHECK_INTS_BLOCKING(ec);
4876 }
while (wait_retryable(&result, lerrno, to, end));
4878 RUBY_VM_CHECK_INTS_BLOCKING(ec);
4885 rb_io_blocking_operation_exit(io, &blocking_operation);
4889 EC_JUMP_TAG(ec, state);
4897 if (fds[0].revents & POLLNVAL) {
4907 if (fds[0].revents & POLLIN_SET)
4908 result |= RB_WAITFD_IN;
4909 if (fds[0].revents & POLLOUT_SET)
4910 result |= RB_WAITFD_OUT;
4911 if (fds[0].revents & POLLEX_SET)
4912 result |= RB_WAITFD_PRI;
4915 if (fds[0].revents & POLLERR_SET)
4936select_single(
VALUE ptr)
4942 args->read, args->write, args->except, args->tv);
4944 args->as.error =
errno;
4947 if (args->read &&
rb_fd_isset(args->as.fd, args->read))
4949 if (args->write &&
rb_fd_isset(args->as.fd, args->write))
4951 if (args->except &&
rb_fd_isset(args->as.fd, args->except))
4958select_single_cleanup(
VALUE ptr)
4962 if (args->blocking_operation) {
4963 rb_io_blocking_operation_exit(args->io, args->blocking_operation);
4995 blocking_operation.ec = th->ec;
4996 rb_io_blocking_operation_enter(io, &blocking_operation);
4997 args.blocking_operation = &blocking_operation;
5001 blocking_operation.ec = NULL;
5002 args.blocking_operation = NULL;
5006 args.read = (events & RB_WAITFD_IN) ? init_set_fd(fd, &rfds) : NULL;
5007 args.write = (events & RB_WAITFD_OUT) ? init_set_fd(fd, &wfds) : NULL;
5008 args.except = (events & RB_WAITFD_PRI) ? init_set_fd(fd, &efds) : NULL;
5011 int result = (int)
rb_ensure(select_single, ptr, select_single_cleanup, ptr);
5013 errno = args.as.error;
5020rb_thread_wait_for_single_fd(
rb_thread_t *th,
int fd,
int events,
struct timeval *timeout)
5022 return thread_io_wait(th, NULL, fd, events, timeout);
5028 return thread_io_wait(th, io, io->
fd, events, timeout);
5035#ifdef USE_CONSERVATIVE_STACK_END
5037rb_gc_set_stack_end(
VALUE **stack_end_p)
5040COMPILER_WARNING_PUSH
5041#if RBIMPL_COMPILER_IS(GCC)
5042COMPILER_WARNING_IGNORED(-Wdangling-pointer);
5044 *stack_end_p = &stack_end;
5057 if (rb_signal_buff_size() > 0) {
5059 threadptr_trap_interrupt(mth);
5064async_bug_fd(
const char *mesg,
int errno_arg,
int fd)
5067 size_t n = strlcpy(buff, mesg,
sizeof(buff));
5068 if (n <
sizeof(buff)-3) {
5071 rb_async_bug_errno(buff, errno_arg);
5076consume_communication_pipe(
int fd)
5082 static char buff[1024];
5088 result = read(fd, buff,
sizeof(buff));
5090 RUBY_DEBUG_LOG(
"resultf:%d buff:%lu", (
int)result, (
unsigned long)buff[0]);
5092 RUBY_DEBUG_LOG(
"result:%d", (
int)result);
5096 if (USE_EVENTFD || result < (ssize_t)
sizeof(buff)) {
5100 else if (result == 0) {
5103 else if (result < 0) {
5109#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
5114 async_bug_fd(
"consume_communication_pipe: read", e, fd);
5121rb_thread_stop_timer_thread(
void)
5123 if (TIMER_THREAD_CREATED_P() && native_stop_timer_thread()) {
5124 native_reset_timer_thread();
5129rb_thread_reset_timer_thread(
void)
5131 native_reset_timer_thread();
5135rb_thread_start_timer_thread(
void)
5138 rb_thread_create_timer_thread();
5142clear_coverage_i(st_data_t key, st_data_t val, st_data_t dummy)
5150 if (GET_VM()->coverage_mode & COVERAGE_TARGET_ONESHOT_LINES) {
5172rb_clear_coverages(
void)
5174 VALUE coverages = rb_get_coverages();
5175 if (
RTEST(coverages)) {
5180#if defined(HAVE_WORKING_FORK)
5188 vm->ractor.main_ractor = r;
5189 vm->ractor.main_thread = th;
5190 r->threads.main = th;
5191 r->status_ = ractor_created;
5193 thread_sched_atfork(TH_SCHED(th));
5198 ccan_list_for_each(&vm->ractor.set, r, vmlr_node) {
5199 if (r != vm->ractor.main_ractor) {
5200 rb_ractor_terminate_atfork(vm, r);
5202 ccan_list_for_each(&r->threads.set, i, lt_node) {
5206 rb_vm_living_threads_init(vm);
5208 rb_ractor_atfork(vm, th);
5209 rb_vm_postponed_job_atfork();
5215 rb_gc_zombie_objspaces_atfork();
5216 rb_gc_atfork_global_locks();
5217 rb_generic_fields_lock_atfork();
5218 ccan_list_head_init(&th->interrupt_exec_tasks);
5221 rb_ractor_sleeper_threads_clear(th->ractor);
5222 rb_clear_coverages();
5225 rb_thread_reset_timer_thread();
5226 rb_thread_start_timer_thread();
5228 VM_ASSERT(vm->ractor.blocking_cnt == 0);
5229 VM_ASSERT(vm->ractor.cnt == 1);
5235 if (th != current_th) {
5237 th->scheduler =
Qnil;
5240 rb_mutex_abandon_keeping_mutexes(th);
5241 rb_mutex_abandon_locking_mutex(th);
5242 thread_cleanup_func(th, TRUE);
5251 rb_threadptr_pending_interrupt_clear(th);
5252 rb_thread_atfork_internal(th, terminate_atfork_i);
5253 th->join_list = NULL;
5254 th->scheduler =
Qnil;
5255 rb_fiber_atfork(th);
5264 if (th != current_th) {
5265 thread_cleanup_func_before_exec(th);
5273 rb_thread_atfork_internal(th, terminate_atfork_before_exec_i);
5298 0, 0, RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE
5321thgroup_s_alloc(
VALUE klass)
5342thgroup_list(
VALUE group)
5348 ccan_list_for_each(&r->threads.set, th, lt_node) {
5349 if (th->thgroup == group) {
5374thgroup_enclose(
VALUE group)
5393thgroup_enclosed_p(
VALUE group)
5398 return RBOOL(data->enclosed);
5438 if (data->enclosed) {
5446 if (data->enclosed) {
5448 "can't move from the enclosed thread group");
5451 target_th->thgroup = group;
5459thread_shield_mark(
void *ptr)
5461 rb_gc_mark((
VALUE)ptr);
5466 {thread_shield_mark, 0, 0,},
5467 0, 0, RUBY_TYPED_THREAD_SAFE_FREE
5471thread_shield_alloc(
VALUE klass)
5476#define GetThreadShieldPtr(obj) ((VALUE)rb_check_typeddata((obj), &thread_shield_data_type))
5477#define THREAD_SHIELD_WAITING_MASK (((FL_USER19-1)&~(FL_USER0-1))|FL_USER19)
5478#define THREAD_SHIELD_WAITING_SHIFT (FL_USHIFT)
5479#define THREAD_SHIELD_WAITING_MAX (THREAD_SHIELD_WAITING_MASK>>THREAD_SHIELD_WAITING_SHIFT)
5480STATIC_ASSERT(THREAD_SHIELD_WAITING_MAX, THREAD_SHIELD_WAITING_MAX <= UINT_MAX);
5481static inline unsigned int
5482rb_thread_shield_waiting(
VALUE b)
5484 return ((
RBASIC(b)->flags&THREAD_SHIELD_WAITING_MASK)>>THREAD_SHIELD_WAITING_SHIFT);
5488rb_thread_shield_waiting_inc(
VALUE b)
5490 unsigned int w = rb_thread_shield_waiting(b);
5492 if (w > THREAD_SHIELD_WAITING_MAX)
5494 RBASIC(b)->flags &= ~THREAD_SHIELD_WAITING_MASK;
5495 RBASIC(b)->flags |= ((
VALUE)w << THREAD_SHIELD_WAITING_SHIFT);
5499rb_thread_shield_waiting_dec(
VALUE b)
5501 unsigned int w = rb_thread_shield_waiting(b);
5504 RBASIC(b)->flags &= ~THREAD_SHIELD_WAITING_MASK;
5505 RBASIC(b)->flags |= ((
VALUE)w << THREAD_SHIELD_WAITING_SHIFT);
5509rb_thread_shield_new(
void)
5511 VALUE thread_shield = thread_shield_alloc(rb_cThreadShield);
5513 return thread_shield;
5517rb_thread_shield_owned(
VALUE self)
5519 VALUE mutex = GetThreadShieldPtr(self);
5520 if (!mutex)
return false;
5524 return m->ec_serial == rb_ec_serial(GET_EC());
5536rb_thread_shield_wait(
VALUE self)
5538 VALUE mutex = GetThreadShieldPtr(self);
5541 if (!mutex)
return Qfalse;
5542 m = mutex_ptr(mutex);
5543 if (m->ec_serial == rb_ec_serial(GET_EC()))
return Qnil;
5544 rb_thread_shield_waiting_inc(self);
5546 rb_thread_shield_waiting_dec(self);
5549 return rb_thread_shield_waiting(self) > 0 ?
Qnil :
Qfalse;
5553thread_shield_get_mutex(
VALUE self)
5555 VALUE mutex = GetThreadShieldPtr(self);
5557 rb_raise(
rb_eThreadError,
"destroyed thread shield - %p", (
void *)self);
5565rb_thread_shield_release(
VALUE self)
5567 VALUE mutex = thread_shield_get_mutex(self);
5569 return RBOOL(rb_thread_shield_waiting(self) > 0);
5576rb_thread_shield_destroy(
VALUE self)
5578 VALUE mutex = thread_shield_get_mutex(self);
5581 return RBOOL(rb_thread_shield_waiting(self) > 0);
5587 return th->ec->local_storage_recursive_hash;
5593 th->ec->local_storage_recursive_hash = hash;
5605recursive_list_access(
VALUE sym)
5608 VALUE hash = threadptr_recursive_hash(th);
5611 hash = rb_ident_hash_new();
5612 threadptr_recursive_hash_set(th, hash);
5616 list = rb_hash_aref(hash, sym);
5619 list = rb_ident_hash_new();
5620 rb_hash_aset(hash, sym, list);
5634#if SIZEOF_LONG == SIZEOF_VOIDP
5635 #define OBJ_ID_EQL(obj_id, other) ((obj_id) == (other))
5636#elif SIZEOF_LONG_LONG == SIZEOF_VOIDP
5637 #define OBJ_ID_EQL(obj_id, other) (RB_BIGNUM_TYPE_P((obj_id)) ? \
5638 rb_big_eql((obj_id), (other)) : ((obj_id) == (other)))
5641 VALUE pair_list = rb_hash_lookup2(list, obj,
Qundef);
5642 if (UNDEF_P(pair_list))
5644 if (paired_obj_id) {
5646 if (!OBJ_ID_EQL(paired_obj_id, pair_list))
5650 if (
NIL_P(rb_hash_lookup(pair_list, paired_obj_id)))
5672 rb_hash_aset(list, obj,
Qtrue);
5674 else if (UNDEF_P(pair_list = rb_hash_lookup2(list, obj,
Qundef))) {
5675 rb_hash_aset(list, obj, paired_obj);
5679 VALUE other_paired_obj = pair_list;
5680 pair_list = rb_hash_new();
5681 rb_hash_aset(pair_list, other_paired_obj,
Qtrue);
5682 rb_hash_aset(list, obj, pair_list);
5684 rb_hash_aset(pair_list, paired_obj,
Qtrue);
5700 VALUE pair_list = rb_hash_lookup2(list, obj,
Qundef);
5701 if (UNDEF_P(pair_list)) {
5705 rb_hash_delete_entry(pair_list, paired_obj);
5711 rb_hash_delete_entry(list, obj);
5727 return (*p->func)(p->obj, p->arg, FALSE);
5748 p.list = recursive_list_access(sym);
5752 outermost = outer && !recursive_check(p.list,
ID2SYM(recursive_key), 0);
5754 if (recursive_check(p.list, p.obj, pairid)) {
5755 if (outer && !outermost) {
5758 return (*func)(obj, arg, TRUE);
5761 enum ruby_tag_type state;
5766 recursive_push(p.list,
ID2SYM(recursive_key), 0);
5767 recursive_push(p.list, p.obj, p.pairid);
5768 result = rb_catch_protect(p.list, exec_recursive_i, (
VALUE)&p, &state);
5769 if (!recursive_pop(p.list, p.obj, p.pairid))
goto invalid;
5770 if (!recursive_pop(p.list,
ID2SYM(recursive_key), 0))
goto invalid;
5771 if (state != TAG_NONE) EC_JUMP_TAG(GET_EC(), state);
5772 if (result == p.list) {
5773 result = (*func)(obj, arg, TRUE);
5778 recursive_push(p.list, p.obj, p.pairid);
5779 EC_PUSH_TAG(GET_EC());
5780 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
5781 ret = (*func)(obj, arg, FALSE);
5784 if (!recursive_pop(p.list, p.obj, p.pairid)) {
5787 if (state != TAG_NONE) EC_JUMP_TAG(GET_EC(), state);
5796 "for %+"PRIsVALUE
" in %+"PRIsVALUE,
5820 return exec_recursive(func, obj, rb_memory_id(paired_obj), arg, 0,
rb_frame_last_func());
5838 return exec_recursive(func, obj, 0, arg, 1, mid);
5850 return exec_recursive(func, obj, rb_memory_id(paired_obj), arg, 1,
rb_frame_last_func());
5862rb_thread_backtrace_m(
int argc,
VALUE *argv,
VALUE thval)
5864 return rb_vm_thread_backtrace(argc, argv, thval);
5879rb_thread_backtrace_locations_m(
int argc,
VALUE *argv,
VALUE thval)
5881 return rb_vm_thread_backtrace_locations(argc, argv, thval);
5885Init_Thread_Mutex(
void)
5976 rb_vm_register_special_exception(ruby_error_stream_closed,
rb_eIOError,
5977 "stream closed in another thread");
5979 cThGroup = rb_define_class(
"ThreadGroup",
rb_cObject);
5986 const char * ptr = getenv(
"RUBY_THREAD_TIMESLICE");
5989 long quantum = strtol(ptr, NULL, 0);
5990 if (quantum > 0 && !(SIZEOF_LONG > 4 && quantum > UINT32_MAX)) {
5991 thread_default_quantum_ms = (uint32_t)quantum;
5994 fprintf(stderr,
"Ignored RUBY_THREAD_TIMESLICE=%s\n", ptr);
5999 th->thgroup = th->ractor->thgroup_default =
rb_obj_alloc(cThGroup);
6000 rb_define_const(cThGroup,
"Default", th->thgroup);
6010#ifdef HAVE_PTHREAD_NP_H
6011 VM_ASSERT(TH_SCHED(th)->running == th);
6018 th->pending_interrupt_queue_checked = 0;
6023 rb_thread_create_timer_thread();
6039#ifdef NON_SCALAR_THREAD_ID
6040 #define thread_id_str(th) (NULL)
6042 #define thread_id_str(th) ((void *)(uintptr_t)(th)->nt->thread_id)
6051 rb_str_catf(msg,
"\n%d threads, %d sleeps current:%p main thread:%p\n",
6052 rb_ractor_living_thread_num(r), rb_ractor_sleeper_thread_num(r),
6053 (
void *)GET_THREAD(), (
void *)r->threads.main);
6055 ccan_list_for_each(&r->threads.set, th, lt_node) {
6056 rb_str_catf(msg,
"* %+"PRIsVALUE
"\n rb_thread_t:%p "
6058 th->self, (
void *)th, th->nt ? thread_id_str(th) :
"N/A", th->ec->interrupt_flag);
6060 if (th->locking_mutex) {
6061 rb_mutex_t *mutex = mutex_ptr(th->locking_mutex);
6062 rb_str_catf(msg,
" mutex:%llu cond:%"PRIuSIZE,
6063 (
unsigned long long)mutex->ec_serial, rb_mutex_num_waiting(mutex));
6069 rb_str_catf(msg,
"\n depended by: tb_thread_id:%p", (
void *)list->thread);
6073 rb_str_catf(msg,
"\n ");
6074 rb_str_concat(msg,
rb_ary_join(rb_ec_backtrace_str_ary(th->ec, RUBY_BACKTRACE_START, RUBY_ALL_BACKTRACE_LINES), sep));
6075 rb_str_catf(msg,
"\n");
6082 if (GET_THREAD()->vm->thread_ignore_deadlock)
return;
6084#ifdef RUBY_THREAD_PTHREAD_H
6085 if (r->threads.sched.readyq_cnt > 0)
return;
6088 int sleeper_num = rb_ractor_sleeper_thread_num(r);
6089 int ltnum = rb_ractor_living_thread_num(r);
6091 if (ltnum > sleeper_num)
return;
6092 if (ltnum < sleeper_num) rb_bug(
"sleeper must not be more than vm_living_thread_num(vm)");
6097 ccan_list_for_each(&r->threads.set, th, lt_node) {
6098 if (th->status != THREAD_STOPPED_FOREVER || RUBY_VM_INTERRUPTED(th->ec)) {
6101 else if (th->locking_mutex) {
6102 rb_mutex_t *mutex = mutex_ptr(th->locking_mutex);
6103 if (mutex->ec_serial == rb_ec_serial(th->ec) || (!mutex->ec_serial && !ccan_list_empty(&mutex->waitq))) {
6114 argv[1] =
rb_str_new2(
"No live threads left. Deadlock?");
6115 debug_deadlock_check(r, argv[1]);
6116 rb_ractor_sleeper_threads_dec(GET_RACTOR());
6117 rb_threadptr_raise(r->threads.main, 2, argv);
6125 VALUE coverage = rb_iseq_coverage(CFP_ISEQ(cfp));
6130 VM_ASSERT(line >= 0);
6134 if (GET_VM()->coverage_mode & COVERAGE_TARGET_ONESHOT_LINES) {
6135 rb_iseq_clear_event_flags(CFP_ISEQ(cfp), CFP_PC(cfp) - ISEQ_BODY(CFP_ISEQ(cfp))->iseq_encoded - 1, RUBY_EVENT_COVERAGE_LINE);
6156 VALUE coverage = rb_iseq_coverage(CFP_ISEQ(cfp));
6160 long pc = CFP_PC(cfp) - ISEQ_BODY(CFP_ISEQ(cfp))->iseq_encoded - 1;
6175 VALUE path, beg_pos_lineno, beg_pos_column, end_pos_lineno, end_pos_column;
6177 if (!me->def)
return NULL;
6180 switch (me->def->type) {
6181 case VM_METHOD_TYPE_ISEQ: {
6184 path = rb_iseq_path(iseq);
6185 beg_pos_lineno =
INT2FIX(loc->code_location.beg_pos.lineno);
6186 beg_pos_column =
INT2FIX(loc->code_location.beg_pos.column);
6187 end_pos_lineno =
INT2FIX(loc->code_location.end_pos.lineno);
6188 end_pos_column =
INT2FIX(loc->code_location.end_pos.column);
6191 case VM_METHOD_TYPE_BMETHOD: {
6192 const rb_iseq_t *iseq = rb_proc_get_iseq(me->def->body.bmethod.proc, 0);
6195 rb_iseq_check(iseq);
6196 path = rb_iseq_path(iseq);
6197 loc = &ISEQ_BODY(iseq)->location;
6198 beg_pos_lineno =
INT2FIX(loc->code_location.beg_pos.lineno);
6199 beg_pos_column =
INT2FIX(loc->code_location.beg_pos.column);
6200 end_pos_lineno =
INT2FIX(loc->code_location.end_pos.lineno);
6201 end_pos_column =
INT2FIX(loc->code_location.end_pos.column);
6206 case VM_METHOD_TYPE_ALIAS:
6207 me = me->def->body.alias.original_me;
6209 case VM_METHOD_TYPE_REFINED:
6210 me = me->def->body.refined.orig_me;
6211 if (!me)
return NULL;
6222 if (resolved_location) {
6223 resolved_location[0] = path;
6224 resolved_location[1] = beg_pos_lineno;
6225 resolved_location[2] = beg_pos_column;
6226 resolved_location[3] = end_pos_lineno;
6227 resolved_location[4] = end_pos_column;
6233 rb_coverage_method_callback *callback;
6245 FIX2LONG(location[1]) <= 0)
return;
6249 .method_id =
ID2SYM(me->def->original_id),
6250 .path = location[0],
6251 .first_lineno = location[1],
6252 .first_column = location[2],
6253 .last_lineno = location[3],
6254 .last_column = location[4],
6257 arg->callback(&method, arg->data);
6278rb_coverage_each_method(rb_coverage_method_callback callback,
void *data)
6281 VALUE me_set = GET_VM()->me_set;
6282 VALUE cme2counter = GET_VM()->cme2counter;
6284 if (
RTEST(me_set)) {
6287 if (
RTEST(cme2counter)) {
6301 me = rb_resolve_me_location(me, 0);
6304 rcount = rb_hash_aref(cme2counter, (
VALUE) me);
6321 if (!
RTEST(GET_VM()->coverages))
return;
6322 if (!(GET_VM()->coverage_mode & COVERAGE_TARGET_METHODS))
return;
6324 VALUE me_set = GET_VM()->me_set;
6325 if (!
RTEST(me_set))
return;
6327 if (rb_resolve_me_location(me, 0) == me) {
6333rb_get_coverages(
void)
6335 return GET_VM()->coverages;
6339rb_get_coverage_mode(
void)
6341 return GET_VM()->coverage_mode;
6345rb_set_coverages(
VALUE coverages,
int mode,
VALUE cme2counter,
VALUE me_set)
6347 GET_VM()->coverages = coverages;
6348 GET_VM()->cme2counter = cme2counter;
6349 GET_VM()->me_set = me_set;
6350 GET_VM()->coverage_mode = mode;
6354rb_resume_coverages(
void)
6356 int mode = GET_VM()->coverage_mode;
6357 VALUE cme2counter = GET_VM()->cme2counter;
6358 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);
6359 if (mode & COVERAGE_TARGET_BRANCHES) {
6360 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);
6362 if (mode & COVERAGE_TARGET_METHODS) {
6368rb_suspend_coverages(
void)
6371 if (GET_VM()->coverage_mode & COVERAGE_TARGET_BRANCHES) {
6374 if (GET_VM()->coverage_mode & COVERAGE_TARGET_METHODS) {
6381rb_reset_coverages(
void)
6383 rb_clear_coverages();
6384 rb_iseq_remove_coverage_all();
6385 GET_VM()->coverages =
Qfalse;
6386 GET_VM()->cme2counter =
Qnil;
6387 GET_VM()->me_set =
Qnil;
6391rb_default_coverage(
int n)
6393 VALUE coverage = rb_ary_hidden_new_fill(3);
6395 int mode = GET_VM()->coverage_mode;
6397 if (mode & COVERAGE_TARGET_LINES) {
6400 RARRAY_ASET(coverage, COVERAGE_INDEX_LINES, lines);
6402 if (mode & COVERAGE_TARGET_BRANCHES) {
6403 branches = rb_ary_hidden_new_fill(2);
6425 VALUE structure = rb_hash_new();
6431 RARRAY_ASET(coverage, COVERAGE_INDEX_BRANCHES, branches);
6437uninterruptible_exit(
VALUE v)
6440 rb_ary_pop(cur_th->pending_interrupt_mask_stack);
6442 cur_th->pending_interrupt_queue_checked = 0;
6443 if (!rb_threadptr_pending_interrupt_empty_p(cur_th)) {
6444 RUBY_VM_SET_INTERRUPT(cur_th->ec);
6452 VALUE interrupt_mask = rb_ident_hash_new();
6455 rb_hash_aset(interrupt_mask,
rb_cObject, sym_never);
6457 rb_ary_push(cur_th->pending_interrupt_mask_stack, interrupt_mask);
6461 RUBY_VM_CHECK_INTS(cur_th->ec);
6468 VM_ASSERT(th->specific_storage == NULL);
6470 if (UNLIKELY(specific_key_count > 0)) {
6471 th->specific_storage =
ZALLOC_N(
void *, RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX);
6475rb_internal_thread_specific_key_t
6480 if (specific_key_count == 0 && vm->ractor.cnt > 1) {
6481 rb_raise(
rb_eThreadError,
"The first rb_internal_thread_specific_key_create() is called with multiple ractors");
6483 else if (specific_key_count > RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX) {
6484 rb_raise(
rb_eThreadError,
"rb_internal_thread_specific_key_create() is called more than %d times", RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX);
6487 rb_internal_thread_specific_key_t key = specific_key_count++;
6494 ccan_list_for_each(&cr->threads.set, th, lt_node) {
6495 thread_specific_storage_alloc(th);
6508 VM_ASSERT(rb_thread_ptr(thread_val) == th);
6509 VM_ASSERT(key < RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX);
6510 VM_ASSERT(th->specific_storage);
6512 return th->specific_storage[key];
6521 VM_ASSERT(rb_thread_ptr(thread_val) == th);
6522 VM_ASSERT(key < RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX);
6523 VM_ASSERT(th->specific_storage);
6525 th->specific_storage[key] = data;
6531 struct ccan_list_node node;
6533 rb_interrupt_exec_func_t *func;
6535 enum rb_interrupt_exec_flag flags;
6539rb_threadptr_interrupt_exec_task_mark(
rb_thread_t *th)
6543 ccan_list_for_each(&th->interrupt_exec_tasks, task, node) {
6544 if (task->flags & rb_interrupt_exec_flag_value_data) {
6545 rb_gc_mark((
VALUE)task->data);
6553rb_threadptr_interrupt_exec(
rb_thread_t *th, rb_interrupt_exec_func_t *func,
void *data,
enum rb_interrupt_exec_flag flags)
6565 ccan_list_add_tail(&th->interrupt_exec_tasks, &task->node);
6566 threadptr_set_interrupt_locked(th,
true);
6583 RUBY_DEBUG_LOG(
"task:%p", task);
6586 if (task->flags & rb_interrupt_exec_flag_new_thread) {
6590 (*task->func)(task->data);
6618 rb_interrupt_exec_func_t *func,
void *data,
enum rb_interrupt_exec_flag flags)
6620 RUBY_DEBUG_LOG(
"flags:%d", (
int)flags);
6623 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().
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 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_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_exc_new(VALUE etype, const char *ptr, long len)
Creates an instance of the passed exception class.
VALUE rb_eException
Mother of all exceptions.
VALUE rb_eThreadError
ThreadError exception.
void rb_exit(int status)
Terminates the current execution context.
VALUE rb_eSignal
SignalException exception.
VALUE rb_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.
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 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.
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.
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 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.
#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_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().
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_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.
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.