61#undef __USE_FORTIFY_LEVEL
62#define __USE_FORTIFY_LEVEL 0
66#include "ruby/internal/config.h"
73#define TH_SCHED(th) (&(th)->ractor->threads.sched)
75#include "eval_intern.h"
78#include "internal/class.h"
79#include "internal/cont.h"
80#include "internal/error.h"
81#include "internal/gc.h"
82#include "internal/hash.h"
83#include "internal/io.h"
84#include "internal/object.h"
85#include "internal/proc.h"
87#include "internal/signal.h"
88#include "internal/thread.h"
89#include "internal/time.h"
90#include "internal/warnings.h"
98#include "ractor_core.h"
102#ifndef USE_NATIVE_THREAD_PRIORITY
103#define USE_NATIVE_THREAD_PRIORITY 0
104#define RUBY_THREAD_PRIORITY_MAX 3
105#define RUBY_THREAD_PRIORITY_MIN -3
108static VALUE rb_cThreadShield;
110static VALUE sym_immediate;
111static VALUE sym_on_blocking;
112static VALUE sym_never;
114static uint32_t thread_default_quantum_ms = 100;
116#define THREAD_LOCAL_STORAGE_INITIALISED FL_USER13
117#define THREAD_LOCAL_STORAGE_INITIALISED_P(th) RB_FL_TEST_RAW((th), THREAD_LOCAL_STORAGE_INITIALISED)
120rb_thread_local_storage(
VALUE thread)
122 if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
130 SLEEP_DEADLOCKABLE = 0x01,
131 SLEEP_SPURIOUS_CHECK = 0x02,
132 SLEEP_ALLOW_SPURIOUS = 0x04,
133 SLEEP_NO_CHECKINTS = 0x08,
136static void sleep_forever(
rb_thread_t *th,
unsigned int fl);
137static int sleep_hrtime(
rb_thread_t *, rb_hrtime_t,
unsigned int fl);
139static void rb_thread_sleep_deadly_allow_spurious_wakeup(
VALUE blocker,
VALUE timeout, rb_hrtime_t end);
142static int rb_threadptr_pending_interrupt_empty_p(
const rb_thread_t *th);
143static const char *thread_status_name(
rb_thread_t *th,
int detail);
144static int hrtime_update_expire(rb_hrtime_t *,
const rb_hrtime_t);
145NORETURN(
static void async_bug_fd(
const char *mesg,
int errno_arg,
int fd));
146MAYBE_UNUSED(
static int consume_communication_pipe(
int fd));
148static volatile int system_working = 1;
149static rb_internal_thread_specific_key_t specific_key_count;
152 struct ccan_list_node wfd_node;
160#define THREAD_SYSTEM_DEPENDENT_IMPLEMENTATION
163 enum rb_thread_status prev_status;
167static void unblock_function_clear(
rb_thread_t *th);
173#define THREAD_BLOCKING_BEGIN(th) do { \
174 struct rb_thread_sched * const sched = TH_SCHED(th); \
175 RB_VM_SAVE_MACHINE_CONTEXT(th); \
176 thread_sched_to_waiting((sched), (th));
178#define THREAD_BLOCKING_END(th) \
179 thread_sched_to_running((sched), (th)); \
180 rb_ractor_thread_switch(th->ractor, th); \
184#ifdef HAVE_BUILTIN___BUILTIN_CHOOSE_EXPR_CONSTANT_P
185#define only_if_constant(expr, notconst) __builtin_choose_expr(__builtin_constant_p(expr), (expr), (notconst))
187#define only_if_constant(expr, notconst) (__builtin_constant_p(expr) ? (expr) : (notconst))
190#define only_if_constant(expr, notconst) notconst
192#define BLOCKING_REGION(th, exec, ubf, ubfarg, fail_if_interrupted) do { \
193 struct rb_blocking_region_buffer __region; \
194 if (blocking_region_begin(th, &__region, (ubf), (ubfarg), fail_if_interrupted) || \
196 !only_if_constant(fail_if_interrupted, TRUE)) { \
199 RB_VM_SAVE_MACHINE_CONTEXT(th); \
200 thread_sched_to_waiting(TH_SCHED(th), th); \
202 blocking_region_end(th, &__region); \
210#define RUBY_VM_CHECK_INTS_BLOCKING(ec) vm_check_ints_blocking(ec)
216 if (LIKELY(rb_threadptr_pending_interrupt_empty_p(th))) {
217 if (LIKELY(!RUBY_VM_INTERRUPTED_ANY(ec)))
return FALSE;
220 th->pending_interrupt_queue_checked = 0;
221 RUBY_VM_SET_INTERRUPT(ec);
223 return rb_threadptr_execute_interrupts(th, 1);
229 return vm_check_ints_blocking(ec);
237#if defined(HAVE_POLL)
238# if defined(__linux__)
241# if defined(__FreeBSD_version) && __FreeBSD_version >= 1100000
244# define POLLERR_SET (POLLHUP | POLLERR)
249timeout_prepare(rb_hrtime_t **to, rb_hrtime_t *rel, rb_hrtime_t *end,
253 *rel = rb_timeval2hrtime(timeout);
254 *end = rb_hrtime_add(rb_hrtime_now(), *rel);
262MAYBE_UNUSED(NOINLINE(
static int thread_start_func_2(
rb_thread_t *th,
VALUE *stack_start)));
263MAYBE_UNUSED(
static bool th_has_dedicated_nt(
const rb_thread_t *th));
264MAYBE_UNUSED(
static int waitfd_to_waiting_flag(
int wfd_event));
266#include THREAD_IMPL_SRC
273#ifndef BUSY_WAIT_SIGNALS
274# define BUSY_WAIT_SIGNALS (0)
278# define USE_EVENTFD (0)
281#include "thread_sync.c"
311 if (fail_if_interrupted) {
312 if (RUBY_VM_INTERRUPTED_ANY(th->ec)) {
317 RUBY_VM_CHECK_INTS(th->ec);
321 }
while (!th->ec->raised_flag && RUBY_VM_INTERRUPTED_ANY(th->ec) &&
324 VM_ASSERT(th->unblock.func == NULL);
326 th->unblock.func = func;
327 th->unblock.arg = arg;
337 th->unblock.func = 0;
342threadptr_interrupt_locked(
rb_thread_t *th,
bool trap)
346 RUBY_DEBUG_LOG(
"th:%u trap:%d", rb_th_serial(th), trap);
349 RUBY_VM_SET_TRAP_INTERRUPT(th->ec);
352 RUBY_VM_SET_INTERRUPT(th->ec);
355 if (th->unblock.func != NULL) {
356 (th->unblock.func)(th->unblock.arg);
368 threadptr_interrupt_locked(th, trap);
376 RUBY_DEBUG_LOG(
"th:%u", rb_th_serial(th));
377 threadptr_interrupt(th,
false);
383 threadptr_interrupt(th,
true);
391 ccan_list_for_each(&r->threads.set, th, lt_node) {
392 if (th != main_thread) {
393 RUBY_DEBUG_LOG(
"terminate start th:%u status:%s", rb_th_serial(th), thread_status_name(th, TRUE));
395 rb_threadptr_pending_interrupt_enque(th, RUBY_FATAL_THREAD_TERMINATED);
396 rb_threadptr_interrupt(th);
398 RUBY_DEBUG_LOG(
"terminate done th:%u status:%s", rb_th_serial(th), thread_status_name(th, TRUE));
401 RUBY_DEBUG_LOG(
"main thread th:%u", rb_th_serial(th));
409 while (thread->join_list) {
413 thread->join_list = join_list->next;
417 if (target_thread->scheduler !=
Qnil && join_list->fiber) {
421 rb_threadptr_interrupt(target_thread);
423 switch (target_thread->status) {
425 case THREAD_STOPPED_FOREVER:
426 target_thread->status = THREAD_RUNNABLE;
436rb_threadptr_unlock_all_locking_mutexes(
rb_thread_t *th)
438 while (th->keeping_mutexes) {
440 th->keeping_mutexes = mutex->next_mutex;
444 const char *error_message = rb_mutex_unlock_th(mutex, th, mutex->fiber);
445 if (error_message) rb_bug(
"invalid keeping_mutexes: %s", error_message);
454 volatile int sleeping = 0;
456 if (cr->threads.main != th) {
457 rb_bug(
"rb_thread_terminate_all: called by child thread (%p, %p)",
458 (
void *)cr->threads.main, (
void *)th);
462 rb_threadptr_unlock_all_locking_mutexes(th);
465 if (EC_EXEC_TAG() == TAG_NONE) {
467 RUBY_DEBUG_LOG(
"th:%u", rb_th_serial(th));
469 terminate_all(cr, th);
471 while (rb_ractor_living_thread_num(cr) > 1) {
472 rb_hrtime_t rel = RB_HRTIME_PER_SEC;
478 native_sleep(th, &rel);
479 RUBY_VM_CHECK_INTS_BLOCKING(ec);
497void rb_threadptr_root_fiber_terminate(
rb_thread_t *th);
498static void threadptr_interrupt_exec_cleanup(
rb_thread_t *th);
501thread_cleanup_func_before_exec(
void *th_ptr)
504 th->status = THREAD_KILLED;
507 th->ec->machine.stack_start = th->ec->machine.stack_end = NULL;
509 threadptr_interrupt_exec_cleanup(th);
510 rb_threadptr_root_fiber_terminate(th);
514thread_cleanup_func(
void *th_ptr,
int atfork)
518 th->locking_mutex =
Qfalse;
519 thread_cleanup_func_before_exec(th_ptr);
538ruby_thread_init_stack(
rb_thread_t *th,
void *local_in_parent_frame)
540 native_thread_init_stack(th, local_in_parent_frame);
544rb_vm_proc_local_ep(
VALUE proc)
546 const VALUE *ep = vm_proc_ep(proc);
549 return rb_vm_ep_local_ep(ep);
558 int argc,
const VALUE *argv,
int kw_splat,
VALUE passed_block_handler);
563 VALUE args = th->invoke_arg.proc.args;
564 const VALUE *args_ptr;
566 VALUE procval = th->invoke_arg.proc.proc;
568 GetProcPtr(procval, proc);
570 th->ec->errinfo =
Qnil;
571 th->ec->root_lep = rb_vm_proc_local_ep(procval);
572 th->ec->root_svar =
Qfalse;
574 vm_check_ints_blocking(th->ec);
576 if (th->invoke_type == thread_invoke_type_ractor_proc) {
577 VALUE self = rb_ractor_self(th->ractor);
581 rb_ractor_receive_parameters(th->ec, th->ractor, args_len, (
VALUE *)args_ptr);
582 vm_check_ints_blocking(th->ec);
584 return rb_vm_invoke_proc_with_self(
587 th->invoke_arg.proc.kw_splat,
588 VM_BLOCK_HANDLER_NONE
597 th->invoke_arg.proc.args =
Qnil;
603 vm_check_ints_blocking(th->ec);
605 return rb_vm_invoke_proc(
608 th->invoke_arg.proc.kw_splat,
609 VM_BLOCK_HANDLER_NONE
617 native_set_thread_name(th);
620 switch (th->invoke_type) {
621 case thread_invoke_type_proc:
622 result = thread_do_start_proc(th);
625 case thread_invoke_type_ractor_proc:
626 result = thread_do_start_proc(th);
627 rb_ractor_atexit(th->ec, result);
630 case thread_invoke_type_func:
631 result = (*th->invoke_arg.func.func)(th->invoke_arg.func.arg);
634 case thread_invoke_type_none:
635 rb_bug(
"unreachable");
646 RUBY_DEBUG_LOG(
"th:%u", rb_th_serial(th));
647 VM_ASSERT(th != th->vm->ractor.main_thread);
649 enum ruby_tag_type state;
651 rb_thread_t *ractor_main_th = th->ractor->threads.main;
654 if (rb_ractor_status_p(th->ractor, ractor_blocking)) {
657 rb_vm_ractor_blocking_cnt_dec(th->vm, th->ractor, __FILE__, __LINE__);
659 r->r_stdin = rb_io_prep_stdin();
660 r->r_stdout = rb_io_prep_stdout();
661 r->r_stderr = rb_io_prep_stderr();
667 VM_ASSERT(UNDEF_P(th->value));
669 int fiber_scheduler_closed = 0, event_thread_end_hooked = 0;
674 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
677 result = thread_do_start(th);
680 if (!fiber_scheduler_closed) {
681 fiber_scheduler_closed = 1;
685 if (!event_thread_end_hooked) {
686 event_thread_end_hooked = 1;
690 if (state == TAG_NONE) {
694 errinfo = th->ec->errinfo;
696 VALUE exc = rb_vm_make_jump_tag_but_local_jump(state,
Qundef);
697 if (!
NIL_P(exc)) errinfo = exc;
699 if (state == TAG_FATAL) {
700 if (th->invoke_type == thread_invoke_type_ractor_proc) {
701 rb_ractor_atexit(th->ec,
Qnil);
709 if (th->report_on_exception) {
710 VALUE mesg = rb_thread_to_s(th->self);
711 rb_str_cat_cstr(mesg,
" terminated with exception (report_on_exception is true):\n");
712 rb_write_error_str(mesg);
713 rb_ec_error_print(th->ec, errinfo);
716 if (th->invoke_type == thread_invoke_type_ractor_proc) {
717 rb_ractor_atexit_exception(th->ec);
720 if (th->vm->thread_abort_on_exception ||
732 VM_ASSERT(!UNDEF_P(th->value));
734 rb_threadptr_join_list_wakeup(th);
735 rb_threadptr_unlock_all_locking_mutexes(th);
737 if (th->invoke_type == thread_invoke_type_ractor_proc) {
738 rb_thread_terminate_all(th);
739 rb_ractor_teardown(th->ec);
742 th->status = THREAD_KILLED;
743 RUBY_DEBUG_LOG(
"killed th:%u", rb_th_serial(th));
745 if (th->vm->ractor.main_thread == th) {
751 rb_threadptr_raise(ractor_main_th, 1, &errinfo);
756 rb_ec_clear_current_thread_trace_func(th->ec);
759 if (th->locking_mutex !=
Qfalse) {
760 rb_bug(
"thread_start_func_2: locking_mutex must not be set (%p:%"PRIxVALUE
")",
761 (
void *)th, th->locking_mutex);
764 if (ractor_main_th->status == THREAD_KILLED &&
765 th->ractor->threads.cnt <= 2 ) {
767 rb_threadptr_interrupt(ractor_main_th);
770 rb_check_deadlock(th->ractor);
772 rb_fiber_close(th->ec->fiber_ptr);
774 thread_cleanup_func(th, FALSE);
775 VM_ASSERT(th->ec->vm_stack == NULL);
777 if (th->invoke_type == thread_invoke_type_ractor_proc) {
781 thread_sched_to_dead(TH_SCHED(th), th);
782 rb_ractor_living_threads_remove(th->ractor, th);
785 rb_ractor_living_threads_remove(th->ractor, th);
786 thread_sched_to_dead(TH_SCHED(th), th);
793 enum thread_invoke_type type;
806static void thread_specific_storage_alloc(
rb_thread_t *th);
812 rb_thread_t *th = rb_thread_ptr(thval), *current_th = rb_ec_thread_ptr(ec);
815 thread_specific_storage_alloc(th);
819 "can't start a new thread (frozen ThreadGroup)");
822 rb_fiber_inherit_storage(ec, th->ec->fiber_ptr);
824 switch (params->type) {
825 case thread_invoke_type_proc:
826 th->invoke_type = thread_invoke_type_proc;
827 th->invoke_arg.proc.args = params->args;
828 th->invoke_arg.proc.proc = params->proc;
832 case thread_invoke_type_ractor_proc:
833#if RACTOR_CHECK_MODE > 0
834 rb_ractor_setup_belonging_to(thval, rb_ractor_id(params->g));
836 th->invoke_type = thread_invoke_type_ractor_proc;
837 th->ractor = params->g;
838 th->ractor->threads.main = th;
839 th->invoke_arg.proc.proc = rb_proc_isolate_bang(params->proc);
842 rb_ractor_send_parameters(ec, params->g, params->args);
845 case thread_invoke_type_func:
846 th->invoke_type = thread_invoke_type_func;
847 th->invoke_arg.func.func = params->fn;
848 th->invoke_arg.func.arg = (
void *)params->args;
852 rb_bug(
"unreachable");
855 th->priority = current_th->priority;
856 th->thgroup = current_th->thgroup;
858 th->pending_interrupt_queue = rb_ary_hidden_new(0);
859 th->pending_interrupt_queue_checked = 0;
860 th->pending_interrupt_mask_stack = rb_ary_dup(current_th->pending_interrupt_mask_stack);
861 RBASIC_CLEAR_CLASS(th->pending_interrupt_mask_stack);
865 RUBY_DEBUG_LOG(
"r:%u th:%u", rb_ractor_id(th->ractor), rb_th_serial(th));
867 rb_ractor_living_threads_insert(th->ractor, th);
870 err = native_thread_create(th);
872 th->status = THREAD_KILLED;
873 rb_ractor_living_threads_remove(th->ractor, th);
879#define threadptr_initialized(th) ((th)->invoke_type != thread_invoke_type_none)
902thread_s_new(
int argc,
VALUE *argv,
VALUE klass)
905 VALUE thread = rb_thread_alloc(klass);
907 if (GET_RACTOR()->threads.main->status == THREAD_KILLED) {
912 th = rb_thread_ptr(thread);
913 if (!threadptr_initialized(th)) {
914 rb_raise(
rb_eThreadError,
"uninitialized thread - check '%"PRIsVALUE
"#initialize'",
934 .type = thread_invoke_type_proc,
938 return thread_create_core(rb_thread_alloc(klass), ¶ms);
944 if (th->invoke_type == thread_invoke_type_proc) {
945 return rb_proc_location(th->invoke_arg.proc.proc);
961 else if (th->invoke_type != thread_invoke_type_none) {
962 VALUE loc = threadptr_invoke_proc_location(th);
965 "already initialized thread - %"PRIsVALUE
":%"PRIsVALUE,
974 .type = thread_invoke_type_proc,
978 return thread_create_core(thread, ¶ms);
986 .type = thread_invoke_type_func,
990 return thread_create_core(rb_thread_alloc(
rb_cThread), ¶ms);
997 .type = thread_invoke_type_ractor_proc,
1002 return thread_create_core(rb_thread_alloc(
rb_cThread), ¶ms);
1014remove_from_join_list(
VALUE arg)
1019 if (target_thread->status != THREAD_KILLED) {
1022 while (*join_list) {
1023 if (*join_list == p->waiter) {
1024 *join_list = (*join_list)->next;
1028 join_list = &(*join_list)->next;
1038 return th->status == THREAD_KILLED || !UNDEF_P(th->value);
1042thread_join_sleep(
VALUE arg)
1045 rb_thread_t *target_th = p->target, *th = p->waiter->thread;
1046 rb_hrtime_t end = 0, *limit = p->limit;
1049 end = rb_hrtime_add(*limit, rb_hrtime_now());
1052 while (!thread_finished(target_th)) {
1055 if (scheduler !=
Qnil) {
1058 if (thread_finished(target_th))
break;
1063 sleep_forever(th, SLEEP_DEADLOCKABLE | SLEEP_ALLOW_SPURIOUS | SLEEP_NO_CHECKINTS);
1066 if (hrtime_update_expire(limit, end)) {
1067 RUBY_DEBUG_LOG(
"timeout target_th:%u", rb_th_serial(target_th));
1070 th->status = THREAD_STOPPED;
1071 native_sleep(th, limit);
1073 RUBY_VM_CHECK_INTS_BLOCKING(th->ec);
1074 th->status = THREAD_RUNNABLE;
1076 RUBY_DEBUG_LOG(
"interrupted target_th:%u status:%s", rb_th_serial(target_th), thread_status_name(target_th, TRUE));
1089 if (th == target_th) {
1090 rb_raise(
rb_eThreadError,
"Target thread must not be current thread");
1093 if (th->ractor->threads.main == target_th) {
1097 RUBY_DEBUG_LOG(
"target_th:%u status:%s", rb_th_serial(target_th), thread_status_name(target_th, TRUE));
1099 if (target_th->status != THREAD_KILLED) {
1101 waiter.next = target_th->join_list;
1103 waiter.fiber = rb_fiberptr_blocking(fiber) ? NULL : fiber;
1104 target_th->join_list = &waiter;
1107 arg.waiter = &waiter;
1108 arg.target = target_th;
1109 arg.timeout = timeout;
1117 RUBY_DEBUG_LOG(
"success target_th:%u status:%s", rb_th_serial(target_th), thread_status_name(target_th, TRUE));
1119 if (target_th->ec->errinfo !=
Qnil) {
1120 VALUE err = target_th->ec->errinfo;
1125 RUBY_DEBUG_LOG(
"terminated target_th:%u status:%s", rb_th_serial(target_th), thread_status_name(target_th, TRUE));
1130 rb_bug(
"thread_join: Fixnum (%d) should not reach here.",
FIX2INT(err));
1133 else if (THROW_DATA_P(target_th->ec->errinfo)) {
1134 rb_bug(
"thread_join: THROW_DATA should not reach here.");
1141 return target_th->self;
1184thread_join_m(
int argc,
VALUE *argv,
VALUE self)
1187 rb_hrtime_t rel = 0, *limit = 0;
1198 if (
NIL_P(timeout)) {
1202 rel = rb_sec2hrtime(NUM2TIMET(timeout));
1206 limit = double2hrtime(&rel,
rb_num2dbl(timeout));
1209 return thread_join(rb_thread_ptr(self), timeout, limit);
1227thread_value(
VALUE self)
1230 thread_join(th,
Qnil, 0);
1231 if (UNDEF_P(th->value)) {
1245#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
1246 if (clock_gettime(CLOCK_MONOTONIC, ts) == 0)
1256NOINLINE(rb_hrtime_t rb_hrtime_now(
void));
1263 return rb_timespec2hrtime(&ts);
1270COMPILER_WARNING_PUSH
1271#if defined(__GNUC__) && __GNUC__ == 7 && __GNUC_MINOR__ <= 3
1272COMPILER_WARNING_IGNORED(-Wmaybe-uninitialized)
1275#define PRIu64 PRI_64_PREFIX "u"
1283hrtime_update_expire(rb_hrtime_t *timeout,
const rb_hrtime_t end)
1285 rb_hrtime_t now = rb_hrtime_now();
1287 if (now > end)
return 1;
1289 RUBY_DEBUG_LOG(
"%"PRIu64
" > %"PRIu64
"", (uint64_t)end, (uint64_t)now);
1291 *timeout = end - now;
1297sleep_hrtime(
rb_thread_t *th, rb_hrtime_t rel,
unsigned int fl)
1299 enum rb_thread_status prev_status = th->status;
1301 rb_hrtime_t end = rb_hrtime_add(rb_hrtime_now(), rel);
1303 th->status = THREAD_STOPPED;
1304 RUBY_VM_CHECK_INTS_BLOCKING(th->ec);
1305 while (th->status == THREAD_STOPPED) {
1306 native_sleep(th, &rel);
1307 woke = vm_check_ints_blocking(th->ec);
1308 if (woke && !(fl & SLEEP_SPURIOUS_CHECK))
1310 if (hrtime_update_expire(&rel, end))
1314 th->status = prev_status;
1319sleep_hrtime_until(
rb_thread_t *th, rb_hrtime_t end,
unsigned int fl)
1321 enum rb_thread_status prev_status = th->status;
1323 rb_hrtime_t rel = rb_hrtime_sub(end, rb_hrtime_now());
1325 th->status = THREAD_STOPPED;
1326 RUBY_VM_CHECK_INTS_BLOCKING(th->ec);
1327 while (th->status == THREAD_STOPPED) {
1328 native_sleep(th, &rel);
1329 woke = vm_check_ints_blocking(th->ec);
1330 if (woke && !(fl & SLEEP_SPURIOUS_CHECK))
1332 if (hrtime_update_expire(&rel, end))
1336 th->status = prev_status;
1343 enum rb_thread_status prev_status = th->status;
1344 enum rb_thread_status status;
1347 status = fl & SLEEP_DEADLOCKABLE ? THREAD_STOPPED_FOREVER : THREAD_STOPPED;
1348 th->status = status;
1350 if (!(fl & SLEEP_NO_CHECKINTS)) RUBY_VM_CHECK_INTS_BLOCKING(th->ec);
1352 while (th->status == status) {
1353 if (fl & SLEEP_DEADLOCKABLE) {
1354 rb_ractor_sleeper_threads_inc(th->ractor);
1355 rb_check_deadlock(th->ractor);
1358 native_sleep(th, 0);
1360 if (fl & SLEEP_DEADLOCKABLE) {
1361 rb_ractor_sleeper_threads_dec(th->ractor);
1363 if (fl & SLEEP_ALLOW_SPURIOUS) {
1367 woke = vm_check_ints_blocking(th->ec);
1369 if (woke && !(fl & SLEEP_SPURIOUS_CHECK)) {
1373 th->status = prev_status;
1379 RUBY_DEBUG_LOG(
"forever");
1380 sleep_forever(GET_THREAD(), SLEEP_SPURIOUS_CHECK);
1386 RUBY_DEBUG_LOG(
"deadly");
1387 sleep_forever(GET_THREAD(), SLEEP_DEADLOCKABLE|SLEEP_SPURIOUS_CHECK);
1391rb_thread_sleep_deadly_allow_spurious_wakeup(
VALUE blocker,
VALUE timeout, rb_hrtime_t end)
1394 if (scheduler !=
Qnil) {
1398 RUBY_DEBUG_LOG(
"...");
1400 sleep_hrtime_until(GET_THREAD(), end, SLEEP_SPURIOUS_CHECK);
1403 sleep_forever(GET_THREAD(), SLEEP_DEADLOCKABLE);
1413 sleep_hrtime(th, rb_timeval2hrtime(&time), SLEEP_SPURIOUS_CHECK);
1419 RUBY_VM_CHECK_INTS_BLOCKING(ec);
1432 rb_ec_check_ints(GET_EC());
1440rb_thread_check_trap_pending(
void)
1442 return rb_signal_buff_size() != 0;
1449 return (
int)RUBY_VM_INTERRUPTED(rb_thread_ptr(thval)->ec);
1459rb_thread_schedule_limits(uint32_t limits_us)
1463 RUBY_DEBUG_LOG(
"us:%u", (
unsigned int)limits_us);
1465 if (th->running_time_us >= limits_us) {
1466 RUBY_DEBUG_LOG(
"switch %s",
"start");
1468 RB_VM_SAVE_MACHINE_CONTEXT(th);
1469 thread_sched_yield(TH_SCHED(th), th);
1470 rb_ractor_thread_switch(th->ractor, th);
1472 RUBY_DEBUG_LOG(
"switch %s",
"done");
1480 rb_thread_schedule_limits(0);
1481 RUBY_VM_CHECK_INTS(GET_EC());
1490#ifdef RUBY_ASSERT_CRITICAL_SECTION
1491 VM_ASSERT(ruby_assert_critical_section_entered == 0);
1493 VM_ASSERT(th == GET_THREAD());
1495 region->prev_status = th->status;
1496 if (unblock_function_set(th, ubf, arg, fail_if_interrupted)) {
1497 th->blocking_region_buffer = region;
1498 th->status = THREAD_STOPPED;
1499 rb_ractor_blocking_threads_inc(th->ractor, __FILE__, __LINE__);
1501 RUBY_DEBUG_LOG(
"thread_id:%p", (
void *)th->nt->thread_id);
1513 unblock_function_clear(th);
1515 unregister_ubf_list(th);
1517 thread_sched_to_running(TH_SCHED(th), th);
1518 rb_ractor_thread_switch(th->ractor, th);
1520 th->blocking_region_buffer = 0;
1521 rb_ractor_blocking_threads_dec(th->ractor, __FILE__, __LINE__);
1522 if (th->status == THREAD_STOPPED) {
1523 th->status = region->prev_status;
1526 RUBY_DEBUG_LOG(
"end");
1530 VM_ASSERT(th == GET_THREAD());
1535rb_nogvl(
void *(*func)(
void *),
void *data1,
1541 if (scheduler !=
Qnil) {
1546 if (!UNDEF_P(result)) {
1547 rb_errno_set(state.saved_errno);
1548 return state.result;
1556 rb_vm_t *vm = rb_ec_vm_ptr(ec);
1557 bool is_main_thread = vm->ractor.main_thread == th;
1558 int saved_errno = 0;
1564 else if (ubf && rb_ractor_living_thread_num(th->ractor) == 1 && is_main_thread) {
1566 vm->ubf_async_safe = 1;
1570 rb_vm_t *
volatile saved_vm = vm;
1571 BLOCKING_REGION(th, {
1573 saved_errno = rb_errno();
1577 if (is_main_thread) vm->ubf_async_safe = 0;
1580 RUBY_VM_CHECK_INTS_BLOCKING(ec);
1583 rb_errno_set(saved_errno);
1684 return rb_nogvl(func, data1, ubf, data2, 0);
1688waitfd_to_waiting_flag(
int wfd_event)
1690 return wfd_event << 1;
1702 ccan_list_add(&th->vm->waiting_fds, &wfd->wfd_node);
1708thread_io_wake_pending_closer(
struct waiting_fd *wfd)
1710 bool has_waiter = wfd->busy &&
RB_TEST(wfd->busy->wakeup_mutex);
1719 ccan_list_del(&wfd->wfd_node);
1723 rb_thread_t *th = rb_thread_ptr(wfd->busy->closing_thread);
1724 if (th->scheduler !=
Qnil) {
1736#if defined(USE_MN_THREADS) && USE_MN_THREADS
1737 return !th_has_dedicated_nt(th) && (events || timeout) && th->blocking;
1745thread_io_wait_events(
rb_thread_t *th,
int fd,
int events,
const struct timeval *timeout)
1747#if defined(USE_MN_THREADS) && USE_MN_THREADS
1748 if (thread_io_mn_schedulable(th, events, timeout)) {
1749 rb_hrtime_t rel, *prel;
1752 rel = rb_timeval2hrtime(timeout);
1759 VM_ASSERT(prel || (events & (RB_WAITFD_IN | RB_WAITFD_OUT)));
1761 if (thread_sched_wait_events(TH_SCHED(th), th, fd, waitfd_to_waiting_flag(events), prel)) {
1775blocking_call_retryable_p(
int r,
int eno)
1777 if (r != -1)
return false;
1781#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
1791rb_thread_mn_schedulable(
VALUE thval)
1794 return th->mn_schedulable;
1798rb_thread_io_blocking_call(rb_blocking_function_t *func,
void *data1,
int fd,
int events)
1803 RUBY_DEBUG_LOG(
"th:%u fd:%d ev:%d", rb_th_serial(th), fd, events);
1807 volatile int saved_errno = 0;
1808 enum ruby_tag_type state;
1809 volatile bool prev_mn_schedulable = th->mn_schedulable;
1810 th->mn_schedulable = thread_io_mn_schedulable(th, events, NULL);
1821 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
1822 volatile enum ruby_tag_type saved_state = state;
1826 saved_errno = errno;
1829 th = rb_ec_thread_ptr(ec);
1831 blocking_call_retryable_p((
int)val, saved_errno) &&
1832 thread_io_wait_events(th, fd, events, NULL)) {
1833 RUBY_VM_CHECK_INTS_BLOCKING(ec);
1836 state = saved_state;
1840 th = rb_ec_thread_ptr(ec);
1841 th->mn_schedulable = prev_mn_schedulable;
1850 EC_JUMP_TAG(ec, state);
1853 RUBY_VM_CHECK_INTS_BLOCKING(ec);
1856 if (saved_errno == ETIMEDOUT) {
1860 errno = saved_errno;
1866rb_thread_io_blocking_region(rb_blocking_function_t *func,
void *data1,
int fd)
1868 return rb_thread_io_blocking_call(func, data1, fd, 0);
1913 fprintf(stderr,
"[BUG] rb_thread_call_with_gvl() is called by non-ruby thread\n");
1918 prev_unblock = th->unblock;
1921 rb_bug(
"rb_thread_call_with_gvl: called by a thread which has GVL.");
1924 blocking_region_end(th, brb);
1928 int released = blocking_region_begin(th, brb, prev_unblock.func, prev_unblock.arg, FALSE);
1930 RB_VM_SAVE_MACHINE_CONTEXT(th);
1931 thread_sched_to_waiting(TH_SCHED(th), th);
1945ruby_thread_has_gvl_p(
void)
1949 if (th && th->blocking_region_buffer == 0) {
1966thread_s_pass(
VALUE klass)
1991rb_threadptr_pending_interrupt_clear(
rb_thread_t *th)
1993 rb_ary_clear(th->pending_interrupt_queue);
1999 rb_ary_push(th->pending_interrupt_queue, v);
2000 th->pending_interrupt_queue_checked = 0;
2004threadptr_check_pending_interrupt_queue(
rb_thread_t *th)
2006 if (!th->pending_interrupt_queue) {
2011enum handle_interrupt_timing {
2013 INTERRUPT_IMMEDIATE,
2014 INTERRUPT_ON_BLOCKING,
2018static enum handle_interrupt_timing
2021 if (sym == sym_immediate) {
2022 return INTERRUPT_IMMEDIATE;
2024 else if (sym == sym_on_blocking) {
2025 return INTERRUPT_ON_BLOCKING;
2027 else if (sym == sym_never) {
2028 return INTERRUPT_NEVER;
2035static enum handle_interrupt_timing
2039 long mask_stack_len =
RARRAY_LEN(th->pending_interrupt_mask_stack);
2044 for (i=0; i<mask_stack_len; i++) {
2045 mask = mask_stack[mask_stack_len-(i+1)];
2050 return rb_threadptr_pending_interrupt_from_symbol(th, mask);
2062 klass =
RBASIC(mod)->klass;
2064 else if (mod != RCLASS_ORIGIN(mod)) {
2068 if ((sym = rb_hash_aref(mask, klass)) !=
Qnil) {
2069 return rb_threadptr_pending_interrupt_from_symbol(th, sym);
2074 return INTERRUPT_NONE;
2078rb_threadptr_pending_interrupt_empty_p(
const rb_thread_t *th)
2080 return RARRAY_LEN(th->pending_interrupt_queue) == 0;
2087 for (i=0; i<
RARRAY_LEN(th->pending_interrupt_queue); i++) {
2097rb_threadptr_pending_interrupt_deque(
rb_thread_t *th,
enum handle_interrupt_timing timing)
2102 for (i=0; i<
RARRAY_LEN(th->pending_interrupt_queue); i++) {
2105 enum handle_interrupt_timing mask_timing = rb_threadptr_pending_interrupt_check_mask(th,
CLASS_OF(err));
2107 switch (mask_timing) {
2108 case INTERRUPT_ON_BLOCKING:
2109 if (timing != INTERRUPT_ON_BLOCKING) {
2113 case INTERRUPT_NONE:
2114 case INTERRUPT_IMMEDIATE:
2115 rb_ary_delete_at(th->pending_interrupt_queue, i);
2117 case INTERRUPT_NEVER:
2122 th->pending_interrupt_queue_checked = 1;
2125 VALUE err = rb_ary_shift(th->pending_interrupt_queue);
2126 if (rb_threadptr_pending_interrupt_empty_p(th)) {
2127 th->pending_interrupt_queue_checked = 1;
2134threadptr_pending_interrupt_active_p(
rb_thread_t *th)
2141 if (th->pending_interrupt_queue_checked) {
2145 if (rb_threadptr_pending_interrupt_empty_p(th)) {
2157 if (val != sym_immediate && val != sym_on_blocking && val != sym_never) {
2158 rb_raise(rb_eArgError,
"unknown mask signature");
2166 if (
RTEST(*maskp)) {
2168 VALUE prev = *maskp;
2169 *maskp = rb_ident_hash_new();
2174 rb_hash_aset(*maskp, key, val);
2268rb_thread_s_handle_interrupt(
VALUE self,
VALUE mask_arg)
2274 enum ruby_tag_type state;
2277 rb_raise(rb_eArgError,
"block is needed.");
2280 mask_arg = rb_to_hash_type(mask_arg);
2282 if (
OBJ_FROZEN(mask_arg) && rb_hash_compare_by_id_p(mask_arg)) {
2288 if (UNDEF_P(mask)) {
2299 rb_ary_push(th->pending_interrupt_mask_stack, mask);
2300 if (!rb_threadptr_pending_interrupt_empty_p(th)) {
2301 th->pending_interrupt_queue_checked = 0;
2302 RUBY_VM_SET_INTERRUPT(th->ec);
2305 EC_PUSH_TAG(th->ec);
2306 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
2311 rb_ary_pop(th->pending_interrupt_mask_stack);
2312 if (!rb_threadptr_pending_interrupt_empty_p(th)) {
2313 th->pending_interrupt_queue_checked = 0;
2314 RUBY_VM_SET_INTERRUPT(th->ec);
2317 RUBY_VM_CHECK_INTS(th->ec);
2320 EC_JUMP_TAG(th->ec, state);
2337rb_thread_pending_interrupt_p(
int argc,
VALUE *argv,
VALUE target_thread)
2339 rb_thread_t *target_th = rb_thread_ptr(target_thread);
2341 if (!target_th->pending_interrupt_queue) {
2344 if (rb_threadptr_pending_interrupt_empty_p(target_th)) {
2348 VALUE err = argv[0];
2350 rb_raise(
rb_eTypeError,
"class or module required for rescue clause");
2352 return RBOOL(rb_threadptr_pending_interrupt_include_p(target_th, err));
2417rb_thread_s_pending_interrupt_p(
int argc,
VALUE *argv,
VALUE self)
2419 return rb_thread_pending_interrupt_p(argc, argv, GET_THREAD()->self);
2422NORETURN(
static void rb_threadptr_to_kill(
rb_thread_t *th));
2427 rb_threadptr_pending_interrupt_clear(th);
2428 th->status = THREAD_RUNNABLE;
2430 th->ec->errinfo =
INT2FIX(TAG_FATAL);
2431 EC_JUMP_TAG(th->ec, TAG_FATAL);
2442 interrupt = ec->interrupt_flag;
2443 old = ATOMIC_CAS(ec->interrupt_flag, interrupt, interrupt & ec->interrupt_mask);
2444 }
while (old != interrupt);
2445 return interrupt & (
rb_atomic_t)~ec->interrupt_mask;
2448static void threadptr_interrupt_exec_exec(
rb_thread_t *th);
2451rb_threadptr_execute_interrupts(
rb_thread_t *th,
int blocking_timing)
2454 int postponed_job_interrupt = 0;
2457 if (th->ec->raised_flag)
return ret;
2459 while ((interrupt = threadptr_get_interrupts(th)) != 0) {
2461 int timer_interrupt;
2462 int pending_interrupt;
2464 int terminate_interrupt;
2466 timer_interrupt = interrupt & TIMER_INTERRUPT_MASK;
2467 pending_interrupt = interrupt & PENDING_INTERRUPT_MASK;
2468 postponed_job_interrupt = interrupt & POSTPONED_JOB_INTERRUPT_MASK;
2469 trap_interrupt = interrupt & TRAP_INTERRUPT_MASK;
2470 terminate_interrupt = interrupt & TERMINATE_INTERRUPT_MASK;
2472 if (interrupt & VM_BARRIER_INTERRUPT_MASK) {
2477 if (postponed_job_interrupt) {
2478 rb_postponed_job_flush(th->vm);
2481 if (trap_interrupt) {
2483 if (th == th->vm->ractor.main_thread) {
2484 enum rb_thread_status prev_status = th->status;
2486 th->status = THREAD_RUNNABLE;
2488 while ((sig = rb_get_next_signal()) != 0) {
2489 ret |= rb_signal_exec(th, sig);
2492 th->status = prev_status;
2495 if (!ccan_list_empty(&th->interrupt_exec_tasks)) {
2496 enum rb_thread_status prev_status = th->status;
2498 th->status = THREAD_RUNNABLE;
2500 threadptr_interrupt_exec_exec(th);
2502 th->status = prev_status;
2507 if (pending_interrupt && threadptr_pending_interrupt_active_p(th)) {
2508 VALUE err = rb_threadptr_pending_interrupt_deque(th, blocking_timing ? INTERRUPT_ON_BLOCKING : INTERRUPT_NONE);
2509 RUBY_DEBUG_LOG(
"err:%"PRIdVALUE, err);
2515 else if (err == RUBY_FATAL_THREAD_KILLED ||
2516 err == RUBY_FATAL_THREAD_TERMINATED ||
2518 terminate_interrupt = 1;
2521 if (err == th->vm->special_exceptions[ruby_error_stream_closed]) {
2523 err = ruby_vm_special_exception_copy(err);
2526 if (th->status == THREAD_STOPPED ||
2527 th->status == THREAD_STOPPED_FOREVER)
2528 th->status = THREAD_RUNNABLE;
2533 if (terminate_interrupt) {
2534 rb_threadptr_to_kill(th);
2537 if (timer_interrupt) {
2538 uint32_t limits_us = thread_default_quantum_ms * 1000;
2540 if (th->priority > 0)
2541 limits_us <<= th->priority;
2543 limits_us >>= -th->priority;
2545 if (th->status == THREAD_RUNNABLE)
2546 th->running_time_us += 10 * 1000;
2548 VM_ASSERT(th->ec->cfp);
2552 rb_thread_schedule_limits(limits_us);
2559rb_thread_execute_interrupts(
VALUE thval)
2561 rb_threadptr_execute_interrupts(rb_thread_ptr(thval), 1);
2567 rb_threadptr_interrupt(th);
2575 if (rb_threadptr_dead(target_th)) {
2583 exc = rb_make_exception(argc, argv);
2588 if (rb_threadptr_dead(target_th)) {
2592 rb_ec_setup_exception(GET_EC(), exc,
Qundef);
2593 rb_threadptr_pending_interrupt_enque(target_th, exc);
2594 rb_threadptr_interrupt(target_th);
2599rb_threadptr_signal_raise(
rb_thread_t *th,
int sig)
2605 rb_threadptr_raise(th->vm->ractor.main_thread, 2, argv);
2617 rb_threadptr_raise(th->vm->ractor.main_thread, 2, argv);
2623 if (ec->raised_flag & RAISED_EXCEPTION) {
2626 ec->raised_flag |= RAISED_EXCEPTION;
2633 if (!(ec->raised_flag & RAISED_EXCEPTION)) {
2636 ec->raised_flag &= ~RAISED_EXCEPTION;
2643 rb_vm_t *vm = GET_THREAD()->vm;
2645 ccan_list_head_init(&busy->pending_fd_users);
2651 ccan_list_for_each_safe(&vm->waiting_fds, wfd, next, wfd_node) {
2652 if (wfd->fd == fd) {
2656 ccan_list_del(&wfd->wfd_node);
2657 ccan_list_add(&busy->pending_fd_users, &wfd->wfd_node);
2660 err = th->vm->special_exceptions[ruby_error_stream_closed];
2661 rb_threadptr_pending_interrupt_enque(th, err);
2662 rb_threadptr_interrupt(th);
2667 has_any = !ccan_list_empty(&busy->pending_fd_users);
2669 busy->closing_fiber = rb_fiber_current();
2670 wakeup_mutex =
Qnil;
2673 RBASIC_CLEAR_CLASS(wakeup_mutex);
2675 busy->wakeup_mutex = wakeup_mutex;
2689 if (!
RB_TEST(busy->wakeup_mutex)) {
2696 while (!ccan_list_empty(&busy->pending_fd_users)) {
2707 if (rb_notify_fd_close(fd, &busy)) {
2708 rb_notify_fd_close_wait(&busy);
2734thread_raise_m(
int argc,
VALUE *argv,
VALUE self)
2739 threadptr_check_pending_interrupt_queue(target_th);
2740 rb_threadptr_raise(target_th, argc, argv);
2743 if (current_th == target_th) {
2744 RUBY_VM_CHECK_INTS(target_th->ec);
2766 if (target_th->to_kill || target_th->status == THREAD_KILLED) {
2769 if (target_th == target_th->vm->ractor.main_thread) {
2773 RUBY_DEBUG_LOG(
"target_th:%u", rb_th_serial(target_th));
2775 if (target_th == GET_THREAD()) {
2777 rb_threadptr_to_kill(target_th);
2780 threadptr_check_pending_interrupt_queue(target_th);
2781 rb_threadptr_pending_interrupt_enque(target_th, RUBY_FATAL_THREAD_KILLED);
2782 rb_threadptr_interrupt(target_th);
2789rb_thread_to_be_killed(
VALUE thread)
2793 if (target_th->to_kill || target_th->status == THREAD_KILLED) {
2869 if (target_th->status == THREAD_KILLED)
return Qnil;
2871 rb_threadptr_ready(target_th);
2873 if (target_th->status == THREAD_STOPPED ||
2874 target_th->status == THREAD_STOPPED_FOREVER) {
2875 target_th->status = THREAD_RUNNABLE;
2917 "stopping only thread\n\tnote: use sleep to stop forever");
2950 return rb_ractor_thread_list();
2976 return rb_thread_list();
2982 return GET_THREAD()->self;
2995thread_s_current(
VALUE klass)
3003 return GET_RACTOR()->threads.main->self;
3014rb_thread_s_main(
VALUE klass)
3041rb_thread_s_abort_exc(
VALUE _)
3043 return RBOOL(GET_THREAD()->vm->thread_abort_on_exception);
3078rb_thread_s_abort_exc_set(
VALUE self,
VALUE val)
3080 GET_THREAD()->vm->thread_abort_on_exception =
RTEST(val);
3101rb_thread_abort_exc(
VALUE thread)
3103 return RBOOL(rb_thread_ptr(thread)->abort_on_exception);
3121rb_thread_abort_exc_set(
VALUE thread,
VALUE val)
3123 rb_thread_ptr(thread)->abort_on_exception =
RTEST(val);
3171rb_thread_s_report_exc(
VALUE _)
3173 return RBOOL(GET_THREAD()->vm->thread_report_on_exception);
3208rb_thread_s_report_exc_set(
VALUE self,
VALUE val)
3210 GET_THREAD()->vm->thread_report_on_exception =
RTEST(val);
3227rb_thread_s_ignore_deadlock(
VALUE _)
3229 return RBOOL(GET_THREAD()->vm->thread_ignore_deadlock);
3254rb_thread_s_ignore_deadlock_set(
VALUE self,
VALUE val)
3256 GET_THREAD()->vm->thread_ignore_deadlock =
RTEST(val);
3278rb_thread_report_exc(
VALUE thread)
3280 return RBOOL(rb_thread_ptr(thread)->report_on_exception);
3298rb_thread_report_exc_set(
VALUE thread,
VALUE val)
3300 rb_thread_ptr(thread)->report_on_exception =
RTEST(val);
3315rb_thread_group(
VALUE thread)
3317 return rb_thread_ptr(thread)->thgroup;
3323 switch (th->status) {
3324 case THREAD_RUNNABLE:
3325 return th->to_kill ?
"aborting" :
"run";
3326 case THREAD_STOPPED_FOREVER:
3327 if (detail)
return "sleep_forever";
3328 case THREAD_STOPPED:
3340 return th->status == THREAD_KILLED;
3376rb_thread_status(
VALUE thread)
3380 if (rb_threadptr_dead(target_th)) {
3381 if (!
NIL_P(target_th->ec->errinfo) &&
3382 !
FIXNUM_P(target_th->ec->errinfo)) {
3390 return rb_str_new2(thread_status_name(target_th, FALSE));
3410rb_thread_alive_p(
VALUE thread)
3412 return RBOOL(!thread_finished(rb_thread_ptr(thread)));
3430rb_thread_stop_p(
VALUE thread)
3434 if (rb_threadptr_dead(th)) {
3437 return RBOOL(th->status == THREAD_STOPPED || th->status == THREAD_STOPPED_FOREVER);
3448rb_thread_getname(
VALUE thread)
3450 return rb_thread_ptr(thread)->name;
3469 enc = rb_enc_get(name);
3470 if (!rb_enc_asciicompat(enc)) {
3471 rb_raise(rb_eArgError,
"ASCII incompatible encoding (%s)",
3476 target_th->name = name;
3477 if (threadptr_initialized(target_th) && target_th->has_dedicated_nt) {
3478 native_set_another_thread_name(target_th->nt->thread_id, name);
3483#if USE_NATIVE_THREAD_NATIVE_THREAD_ID
3507rb_thread_native_thread_id(
VALUE thread)
3510 if (rb_threadptr_dead(target_th))
return Qnil;
3511 return native_thread_native_thread_id(target_th);
3514# define rb_thread_native_thread_id rb_f_notimplement
3525rb_thread_to_s(
VALUE thread)
3532 status = thread_status_name(target_th, TRUE);
3533 str = rb_sprintf(
"#<%"PRIsVALUE
":%p", cname, (
void *)thread);
3534 if (!
NIL_P(target_th->name)) {
3535 rb_str_catf(str,
"@%"PRIsVALUE, target_th->name);
3537 if ((loc = threadptr_invoke_proc_location(target_th)) !=
Qnil) {
3538 rb_str_catf(str,
" %"PRIsVALUE
":%"PRIsVALUE,
3541 rb_str_catf(str,
" %s>", status);
3547#define recursive_key id__recursive_key__
3552 if (
id == recursive_key) {
3553 return th->ec->local_storage_recursive_hash;
3557 struct rb_id_table *local_storage = th->ec->local_storage;
3559 if (local_storage != NULL && rb_id_table_lookup(local_storage,
id, &val)) {
3571 return threadptr_local_aref(rb_thread_ptr(thread),
id);
3638 if (!
id)
return Qnil;
3656rb_thread_fetch(
int argc,
VALUE *argv,
VALUE self)
3667 if (block_given && argc == 2) {
3668 rb_warn(
"block supersedes default value argument");
3673 if (
id == recursive_key) {
3674 return target_th->ec->local_storage_recursive_hash;
3676 else if (
id && target_th->ec->local_storage &&
3677 rb_id_table_lookup(target_th->ec->local_storage,
id, &val)) {
3680 else if (block_given) {
3683 else if (argc == 1) {
3684 rb_key_err_raise(rb_sprintf(
"key not found: %+"PRIsVALUE, key), self, key);
3694 if (
id == recursive_key) {
3695 th->ec->local_storage_recursive_hash = val;
3699 struct rb_id_table *local_storage = th->ec->local_storage;
3702 if (!local_storage)
return Qnil;
3703 rb_id_table_delete(local_storage,
id);
3707 if (local_storage == NULL) {
3708 th->ec->local_storage = local_storage = rb_id_table_create(0);
3710 rb_id_table_insert(local_storage,
id, val);
3723 return threadptr_local_aset(rb_thread_ptr(thread),
id, val);
3774rb_thread_variable_get(
VALUE thread,
VALUE key)
3779 if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
3782 locals = rb_thread_local_storage(thread);
3783 return rb_hash_aref(locals, symbol);
3804 locals = rb_thread_local_storage(thread);
3826 struct rb_id_table *local_storage = rb_thread_ptr(self)->ec->local_storage;
3828 if (!
id || local_storage == NULL) {
3831 return RBOOL(rb_id_table_lookup(local_storage,
id, &val));
3834static enum rb_id_table_iterator_result
3835thread_keys_i(
ID key,
VALUE value,
void *ary)
3838 return ID_TABLE_CONTINUE;
3845 return rb_ractor_living_thread_num(GET_RACTOR()) == 1;
3863rb_thread_keys(
VALUE self)
3865 struct rb_id_table *local_storage = rb_thread_ptr(self)->ec->local_storage;
3866 VALUE ary = rb_ary_new();
3868 if (local_storage) {
3869 rb_id_table_foreach(local_storage, thread_keys_i, (
void *)ary);
3877 rb_ary_push(ary, key);
3899rb_thread_variables(
VALUE thread)
3905 if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
3908 locals = rb_thread_local_storage(thread);
3936 if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
3939 locals = rb_thread_local_storage(thread);
3941 return RBOOL(rb_hash_lookup(locals, symbol) !=
Qnil);
3960rb_thread_priority(
VALUE thread)
3962 return INT2NUM(rb_thread_ptr(thread)->priority);
3993rb_thread_priority_set(
VALUE thread,
VALUE prio)
3998#if USE_NATIVE_THREAD_PRIORITY
3999 target_th->priority =
NUM2INT(prio);
4000 native_thread_apply_priority(th);
4003 if (priority > RUBY_THREAD_PRIORITY_MAX) {
4004 priority = RUBY_THREAD_PRIORITY_MAX;
4006 else if (priority < RUBY_THREAD_PRIORITY_MIN) {
4007 priority = RUBY_THREAD_PRIORITY_MIN;
4009 target_th->priority = (int8_t)priority;
4011 return INT2NUM(target_th->priority);
4016#if defined(NFDBITS) && defined(HAVE_RB_FD_INIT)
4052 FD_ZERO(fds->
fdset);
4058 size_t size = howmany(
rb_fd_max(src), NFDBITS) *
sizeof(fd_mask);
4060 if (size <
sizeof(fd_set))
4061 size =
sizeof(fd_set);
4085 size_t m = howmany(n + 1, NFDBITS) *
sizeof(fd_mask);
4086 size_t o = howmany(fds->
maxfd, NFDBITS) *
sizeof(fd_mask);
4088 if (m <
sizeof(fd_set)) m =
sizeof(fd_set);
4089 if (o <
sizeof(fd_set)) o =
sizeof(fd_set);
4093 memset((
char *)fds->
fdset + o, 0, m - o);
4102 FD_SET(n, fds->
fdset);
4108 if (n >= fds->
maxfd)
return;
4109 FD_CLR(n, fds->
fdset);
4115 if (n >= fds->
maxfd)
return 0;
4116 return FD_ISSET(n, fds->
fdset) != 0;
4122 size_t size = howmany(max, NFDBITS) *
sizeof(fd_mask);
4124 if (size <
sizeof(fd_set)) size =
sizeof(fd_set);
4127 memcpy(dst->
fdset, src, size);
4133 size_t size = howmany(
rb_fd_max(src), NFDBITS) *
sizeof(fd_mask);
4135 if (size <
sizeof(fd_set))
4136 size =
sizeof(fd_set);
4145 fd_set *r = NULL, *w = NULL, *e = NULL;
4158 return select(n, r, w, e, timeout);
4161#define rb_fd_no_init(fds) ((void)((fds)->fdset = 0), (void)((fds)->maxfd = 0))
4168#define FD_ZERO(f) rb_fd_zero(f)
4169#define FD_SET(i, f) rb_fd_set((i), (f))
4170#define FD_CLR(i, f) rb_fd_clr((i), (f))
4171#define FD_ISSET(i, f) rb_fd_isset((i), (f))
4173#elif defined(_WIN32)
4178 set->
capa = FD_SETSIZE;
4180 FD_ZERO(set->
fdset);
4202 SOCKET s = rb_w32_get_osfhandle(fd);
4204 for (i = 0; i < set->
fdset->fd_count; i++) {
4205 if (set->
fdset->fd_array[i] == s) {
4209 if (set->
fdset->fd_count >= (
unsigned)set->
capa) {
4210 set->
capa = (set->
fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
4212 rb_xrealloc_mul_add(
4213 set->
fdset, set->
capa,
sizeof(SOCKET),
sizeof(
unsigned int));
4215 set->
fdset->fd_array[set->
fdset->fd_count++] = s;
4223#define FD_ZERO(f) rb_fd_zero(f)
4224#define FD_SET(i, f) rb_fd_set((i), (f))
4225#define FD_CLR(i, f) rb_fd_clr((i), (f))
4226#define FD_ISSET(i, f) rb_fd_isset((i), (f))
4228#define rb_fd_no_init(fds) (void)((fds)->fdset = 0)
4232#ifndef rb_fd_no_init
4233#define rb_fd_no_init(fds) (void)(fds)
4237wait_retryable(
volatile int *result,
int errnum, rb_hrtime_t *rel, rb_hrtime_t end)
4247 if (rel && hrtime_update_expire(rel, end)) {
4257 return !hrtime_update_expire(rel, end);
4277select_set_free(
VALUE p)
4292 volatile int result = 0;
4294 rb_hrtime_t *to, rel, end = 0;
4296 timeout_prepare(&to, &rel, &end, set->timeout);
4297 volatile rb_hrtime_t endtime = end;
4298#define restore_fdset(dst, src) \
4299 ((dst) ? rb_fd_dup(dst, src) : (void)0)
4300#define do_select_update() \
4301 (restore_fdset(set->rset, &set->orig_rset), \
4302 restore_fdset(set->wset, &set->orig_wset), \
4303 restore_fdset(set->eset, &set->orig_eset), \
4309 BLOCKING_REGION(set->th, {
4312 if (!RUBY_VM_INTERRUPTED(set->th->ec)) {
4313 result = native_fd_select(set->max,
4314 set->rset, set->wset, set->eset,
4315 rb_hrtime2timeval(&tv, to), set->th);
4316 if (result < 0) lerrno = errno;
4318 }, ubf_select, set->th, TRUE);
4320 RUBY_VM_CHECK_INTS_BLOCKING(set->th->ec);
4321 }
while (wait_retryable(&result, lerrno, to, endtime) && do_select_update());
4327 return (
VALUE)result;
4336 set.th = GET_THREAD();
4337 RUBY_VM_CHECK_INTS_BLOCKING(set.th->ec);
4342 set.timeout = timeout;
4344 if (!set.rset && !set.wset && !set.eset) {
4353#define fd_init_copy(f) do { \
4355 rb_fd_resize(set.max - 1, set.f); \
4356 if (&set.orig_##f != set.f) { \
4357 rb_fd_init_copy(&set.orig_##f, set.f); \
4361 rb_fd_no_init(&set.orig_##f); \
4375#define POLLIN_SET (POLLRDNORM | POLLRDBAND | POLLIN | POLLHUP | POLLERR)
4376#define POLLOUT_SET (POLLWRBAND | POLLWRNORM | POLLOUT | POLLERR)
4377#define POLLEX_SET (POLLPRI)
4380# define POLLERR_SET (0)
4384wait_for_single_fd_blocking_region(
rb_thread_t *th,
struct pollfd *fds, nfds_t nfds,
4385 rb_hrtime_t *
const to,
volatile int *lerrno)
4388 volatile int result = 0;
4391 BLOCKING_REGION(th, {
4392 if (!RUBY_VM_INTERRUPTED(th->ec)) {
4393 result = ppoll(fds, nfds, rb_hrtime2timespec(&ts, to), 0);
4394 if (result < 0) *lerrno = errno;
4396 }, ubf_select, th, TRUE);
4404rb_thread_wait_for_single_fd(
int fd,
int events,
struct timeval *timeout)
4406 struct pollfd fds[1] = {{
4408 .events = (short)events,
4411 volatile int result = 0;
4414 enum ruby_tag_type state;
4415 volatile int lerrno;
4420 thread_io_setup_wfd(th, fd, &wfd);
4422 if (timeout == NULL && thread_io_wait_events(th, fd, events, NULL)) {
4425 fds[0].revents = events;
4429 EC_PUSH_TAG(wfd.th->ec);
4430 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
4431 rb_hrtime_t *to, rel, end = 0;
4432 RUBY_VM_CHECK_INTS_BLOCKING(wfd.th->ec);
4433 timeout_prepare(&to, &rel, &end, timeout);
4435 nfds = numberof(fds);
4436 result = wait_for_single_fd_blocking_region(wfd.th, fds, nfds, to, &lerrno);
4438 RUBY_VM_CHECK_INTS_BLOCKING(wfd.th->ec);
4439 }
while (wait_retryable(&result, lerrno, to, end));
4444 thread_io_wake_pending_closer(&wfd);
4447 EC_JUMP_TAG(wfd.th->ec, state);
4455 if (fds[0].revents & POLLNVAL) {
4465 if (fds[0].revents & POLLIN_SET)
4466 result |= RB_WAITFD_IN;
4467 if (fds[0].revents & POLLOUT_SET)
4468 result |= RB_WAITFD_OUT;
4469 if (fds[0].revents & POLLEX_SET)
4470 result |= RB_WAITFD_PRI;
4473 if (fds[0].revents & POLLERR_SET)
4492select_single(
VALUE ptr)
4498 args->read, args->write, args->except, args->tv);
4500 args->as.error =
errno;
4503 if (args->read &&
rb_fd_isset(args->as.fd, args->read))
4505 if (args->write &&
rb_fd_isset(args->as.fd, args->write))
4507 if (args->except &&
rb_fd_isset(args->as.fd, args->except))
4514select_single_cleanup(
VALUE ptr)
4518 thread_io_wake_pending_closer(&args->wfd);
4539rb_thread_wait_for_single_fd(
int fd,
int events,
struct timeval *timeout)
4549 args.read = (events & RB_WAITFD_IN) ? init_set_fd(fd, &rfds) : NULL;
4550 args.write = (events & RB_WAITFD_OUT) ? init_set_fd(fd, &wfds) : NULL;
4551 args.except = (events & RB_WAITFD_PRI) ? init_set_fd(fd, &efds) : NULL;
4553 thread_io_setup_wfd(th, fd, &args.wfd);
4555 r = (int)
rb_ensure(select_single, ptr, select_single_cleanup, ptr);
4557 errno = args.as.error;
4567#ifdef USE_CONSERVATIVE_STACK_END
4569rb_gc_set_stack_end(
VALUE **stack_end_p)
4572COMPILER_WARNING_PUSH
4573#if __has_warning("-Wdangling-pointer")
4574COMPILER_WARNING_IGNORED(-Wdangling-pointer);
4576 *stack_end_p = &stack_end;
4589 if (rb_signal_buff_size() > 0) {
4591 threadptr_trap_interrupt(mth);
4596async_bug_fd(
const char *mesg,
int errno_arg,
int fd)
4599 size_t n = strlcpy(buff, mesg,
sizeof(buff));
4600 if (n <
sizeof(buff)-3) {
4603 rb_async_bug_errno(buff, errno_arg);
4608consume_communication_pipe(
int fd)
4614 static char buff[1024];
4620 result = read(fd, buff,
sizeof(buff));
4622 RUBY_DEBUG_LOG(
"resultf:%d buff:%lu", (
int)result, (
unsigned long)buff[0]);
4624 RUBY_DEBUG_LOG(
"result:%d", (
int)result);
4628 if (USE_EVENTFD || result < (ssize_t)
sizeof(buff)) {
4632 else if (result == 0) {
4635 else if (result < 0) {
4641#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
4646 async_bug_fd(
"consume_communication_pipe: read", e, fd);
4653rb_thread_stop_timer_thread(
void)
4655 if (TIMER_THREAD_CREATED_P() && native_stop_timer_thread()) {
4656 native_reset_timer_thread();
4661rb_thread_reset_timer_thread(
void)
4663 native_reset_timer_thread();
4667rb_thread_start_timer_thread(
void)
4670 rb_thread_create_timer_thread();
4674clear_coverage_i(st_data_t key, st_data_t val, st_data_t dummy)
4682 if (GET_VM()->coverage_mode & COVERAGE_TARGET_ONESHOT_LINES) {
4683 rb_ary_clear(lines);
4704rb_clear_coverages(
void)
4706 VALUE coverages = rb_get_coverages();
4707 if (
RTEST(coverages)) {
4712#if defined(HAVE_WORKING_FORK)
4720 vm->ractor.main_ractor = r;
4721 vm->ractor.main_thread = th;
4722 r->threads.main = th;
4723 r->status_ = ractor_created;
4725 thread_sched_atfork(TH_SCHED(th));
4729 ccan_list_for_each(&vm->ractor.set, r, vmlr_node) {
4730 ccan_list_for_each(&r->threads.set, i, lt_node) {
4734 rb_vm_living_threads_init(vm);
4736 rb_ractor_atfork(vm, th);
4737 rb_vm_postponed_job_atfork();
4741 ccan_list_head_init(&th->interrupt_exec_tasks);
4744 rb_ractor_sleeper_threads_clear(th->ractor);
4745 rb_clear_coverages();
4748 rb_thread_reset_timer_thread();
4749 rb_thread_start_timer_thread();
4751 VM_ASSERT(vm->ractor.blocking_cnt == 0);
4752 VM_ASSERT(vm->ractor.cnt == 1);
4758 if (th != current_th) {
4759 rb_mutex_abandon_keeping_mutexes(th);
4760 rb_mutex_abandon_locking_mutex(th);
4761 thread_cleanup_func(th, TRUE);
4770 rb_threadptr_pending_interrupt_clear(th);
4771 rb_thread_atfork_internal(th, terminate_atfork_i);
4772 th->join_list = NULL;
4773 rb_fiber_atfork(th);
4782 if (th != current_th) {
4783 thread_cleanup_func_before_exec(th);
4791 rb_thread_atfork_internal(th, terminate_atfork_before_exec_i);
4816 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE
4839thgroup_s_alloc(
VALUE klass)
4860thgroup_list(
VALUE group)
4862 VALUE ary = rb_ary_new();
4866 ccan_list_for_each(&r->threads.set, th, lt_node) {
4867 if (th->thgroup == group) {
4868 rb_ary_push(ary, th->self);
4892thgroup_enclose(
VALUE group)
4911thgroup_enclosed_p(
VALUE group)
4916 return RBOOL(data->enclosed);
4956 if (data->enclosed) {
4964 if (data->enclosed) {
4966 "can't move from the enclosed thread group");
4969 target_th->thgroup = group;
4977thread_shield_mark(
void *ptr)
4979 rb_gc_mark((
VALUE)ptr);
4984 {thread_shield_mark, 0, 0,},
4985 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
4989thread_shield_alloc(
VALUE klass)
4994#define GetThreadShieldPtr(obj) ((VALUE)rb_check_typeddata((obj), &thread_shield_data_type))
4995#define THREAD_SHIELD_WAITING_MASK (((FL_USER19-1)&~(FL_USER0-1))|FL_USER19)
4996#define THREAD_SHIELD_WAITING_SHIFT (FL_USHIFT)
4997#define THREAD_SHIELD_WAITING_MAX (THREAD_SHIELD_WAITING_MASK>>THREAD_SHIELD_WAITING_SHIFT)
4998STATIC_ASSERT(THREAD_SHIELD_WAITING_MAX, THREAD_SHIELD_WAITING_MAX <= UINT_MAX);
4999static inline unsigned int
5000rb_thread_shield_waiting(
VALUE b)
5002 return ((
RBASIC(b)->flags&THREAD_SHIELD_WAITING_MASK)>>THREAD_SHIELD_WAITING_SHIFT);
5006rb_thread_shield_waiting_inc(
VALUE b)
5008 unsigned int w = rb_thread_shield_waiting(b);
5010 if (w > THREAD_SHIELD_WAITING_MAX)
5012 RBASIC(b)->flags &= ~THREAD_SHIELD_WAITING_MASK;
5013 RBASIC(b)->flags |= ((
VALUE)w << THREAD_SHIELD_WAITING_SHIFT);
5017rb_thread_shield_waiting_dec(
VALUE b)
5019 unsigned int w = rb_thread_shield_waiting(b);
5022 RBASIC(b)->flags &= ~THREAD_SHIELD_WAITING_MASK;
5023 RBASIC(b)->flags |= ((
VALUE)w << THREAD_SHIELD_WAITING_SHIFT);
5027rb_thread_shield_new(
void)
5029 VALUE thread_shield = thread_shield_alloc(rb_cThreadShield);
5031 return thread_shield;
5035rb_thread_shield_owned(
VALUE self)
5037 VALUE mutex = GetThreadShieldPtr(self);
5038 if (!mutex)
return false;
5042 return m->fiber == GET_EC()->fiber_ptr;
5054rb_thread_shield_wait(
VALUE self)
5056 VALUE mutex = GetThreadShieldPtr(self);
5059 if (!mutex)
return Qfalse;
5060 m = mutex_ptr(mutex);
5061 if (m->fiber == GET_EC()->fiber_ptr)
return Qnil;
5062 rb_thread_shield_waiting_inc(self);
5064 rb_thread_shield_waiting_dec(self);
5067 return rb_thread_shield_waiting(self) > 0 ?
Qnil :
Qfalse;
5071thread_shield_get_mutex(
VALUE self)
5073 VALUE mutex = GetThreadShieldPtr(self);
5075 rb_raise(
rb_eThreadError,
"destroyed thread shield - %p", (
void *)self);
5083rb_thread_shield_release(
VALUE self)
5085 VALUE mutex = thread_shield_get_mutex(self);
5087 return RBOOL(rb_thread_shield_waiting(self) > 0);
5094rb_thread_shield_destroy(
VALUE self)
5096 VALUE mutex = thread_shield_get_mutex(self);
5099 return RBOOL(rb_thread_shield_waiting(self) > 0);
5105 return th->ec->local_storage_recursive_hash;
5111 th->ec->local_storage_recursive_hash = hash;
5123recursive_list_access(
VALUE sym)
5126 VALUE hash = threadptr_recursive_hash(th);
5129 hash = rb_ident_hash_new();
5130 threadptr_recursive_hash_set(th, hash);
5134 list = rb_hash_aref(hash, sym);
5137 list = rb_ident_hash_new();
5138 rb_hash_aset(hash, sym, list);
5152#if SIZEOF_LONG == SIZEOF_VOIDP
5153 #define OBJ_ID_EQL(obj_id, other) ((obj_id) == (other))
5154#elif SIZEOF_LONG_LONG == SIZEOF_VOIDP
5155 #define OBJ_ID_EQL(obj_id, other) (RB_BIGNUM_TYPE_P((obj_id)) ? \
5156 rb_big_eql((obj_id), (other)) : ((obj_id) == (other)))
5159 VALUE pair_list = rb_hash_lookup2(list, obj,
Qundef);
5160 if (UNDEF_P(pair_list))
5162 if (paired_obj_id) {
5164 if (!OBJ_ID_EQL(paired_obj_id, pair_list))
5168 if (
NIL_P(rb_hash_lookup(pair_list, paired_obj_id)))
5190 rb_hash_aset(list, obj,
Qtrue);
5192 else if (UNDEF_P(pair_list = rb_hash_lookup2(list, obj,
Qundef))) {
5193 rb_hash_aset(list, obj, paired_obj);
5197 VALUE other_paired_obj = pair_list;
5198 pair_list = rb_hash_new();
5199 rb_hash_aset(pair_list, other_paired_obj,
Qtrue);
5200 rb_hash_aset(list, obj, pair_list);
5202 rb_hash_aset(pair_list, paired_obj,
Qtrue);
5218 VALUE pair_list = rb_hash_lookup2(list, obj,
Qundef);
5219 if (UNDEF_P(pair_list)) {
5223 rb_hash_delete_entry(pair_list, paired_obj);
5229 rb_hash_delete_entry(list, obj);
5245 return (*p->func)(p->obj, p->arg, FALSE);
5266 p.list = recursive_list_access(sym);
5270 outermost = outer && !recursive_check(p.list,
ID2SYM(recursive_key), 0);
5272 if (recursive_check(p.list, p.obj, pairid)) {
5273 if (outer && !outermost) {
5276 return (*func)(obj, arg, TRUE);
5279 enum ruby_tag_type state;
5284 recursive_push(p.list,
ID2SYM(recursive_key), 0);
5285 recursive_push(p.list, p.obj, p.pairid);
5286 result = rb_catch_protect(p.list, exec_recursive_i, (
VALUE)&p, &state);
5287 if (!recursive_pop(p.list, p.obj, p.pairid))
goto invalid;
5288 if (!recursive_pop(p.list,
ID2SYM(recursive_key), 0))
goto invalid;
5289 if (state != TAG_NONE) EC_JUMP_TAG(GET_EC(), state);
5290 if (result == p.list) {
5291 result = (*func)(obj, arg, TRUE);
5296 recursive_push(p.list, p.obj, p.pairid);
5297 EC_PUSH_TAG(GET_EC());
5298 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
5299 ret = (*func)(obj, arg, FALSE);
5302 if (!recursive_pop(p.list, p.obj, p.pairid)) {
5305 if (state != TAG_NONE) EC_JUMP_TAG(GET_EC(), state);
5314 "for %+"PRIsVALUE
" in %+"PRIsVALUE,
5338 return exec_recursive(func, obj, rb_memory_id(paired_obj), arg, 0,
rb_frame_last_func());
5356 return exec_recursive(func, obj, 0, arg, 1, mid);
5368 return exec_recursive(func, obj, rb_memory_id(paired_obj), arg, 1,
rb_frame_last_func());
5380rb_thread_backtrace_m(
int argc,
VALUE *argv,
VALUE thval)
5382 return rb_vm_thread_backtrace(argc, argv, thval);
5397rb_thread_backtrace_locations_m(
int argc,
VALUE *argv,
VALUE thval)
5399 return rb_vm_thread_backtrace_locations(argc, argv, thval);
5403Init_Thread_Mutex(
void)
5493 rb_vm_register_special_exception(ruby_error_stream_closed,
rb_eIOError,
5494 "stream closed in another thread");
5503 const char * ptr = getenv(
"RUBY_THREAD_TIMESLICE");
5506 long quantum = strtol(ptr, NULL, 0);
5507 if (quantum > 0 && !(SIZEOF_LONG > 4 && quantum > UINT32_MAX)) {
5508 thread_default_quantum_ms = (uint32_t)quantum;
5511 fprintf(stderr,
"Ignored RUBY_THREAD_TIMESLICE=%s\n", ptr);
5516 th->thgroup = th->ractor->thgroup_default =
rb_obj_alloc(cThGroup);
5517 rb_define_const(cThGroup,
"Default", th->thgroup);
5527#ifdef HAVE_PTHREAD_NP_H
5528 VM_ASSERT(TH_SCHED(th)->running == th);
5534 th->pending_interrupt_queue = rb_ary_hidden_new(0);
5535 th->pending_interrupt_queue_checked = 0;
5536 th->pending_interrupt_mask_stack = rb_ary_hidden_new(0);
5540 rb_thread_create_timer_thread();
5556#ifdef NON_SCALAR_THREAD_ID
5557 #define thread_id_str(th) (NULL)
5559 #define thread_id_str(th) ((void *)(uintptr_t)(th)->nt->thread_id)
5568 rb_str_catf(msg,
"\n%d threads, %d sleeps current:%p main thread:%p\n",
5569 rb_ractor_living_thread_num(r), rb_ractor_sleeper_thread_num(r),
5570 (
void *)GET_THREAD(), (
void *)r->threads.main);
5572 ccan_list_for_each(&r->threads.set, th, lt_node) {
5573 rb_str_catf(msg,
"* %+"PRIsVALUE
"\n rb_thread_t:%p "
5575 th->self, (
void *)th, th->nt ? thread_id_str(th) :
"N/A", th->ec->interrupt_flag);
5577 if (th->locking_mutex) {
5578 rb_mutex_t *mutex = mutex_ptr(th->locking_mutex);
5579 rb_str_catf(msg,
" mutex:%p cond:%"PRIuSIZE,
5580 (
void *)mutex->fiber, rb_mutex_num_waiting(mutex));
5586 rb_str_catf(msg,
"\n depended by: tb_thread_id:%p", (
void *)list->thread);
5590 rb_str_catf(msg,
"\n ");
5591 rb_str_concat(msg, rb_ary_join(rb_ec_backtrace_str_ary(th->ec, RUBY_BACKTRACE_START, RUBY_ALL_BACKTRACE_LINES), sep));
5592 rb_str_catf(msg,
"\n");
5599 if (GET_THREAD()->vm->thread_ignore_deadlock)
return;
5601#ifdef RUBY_THREAD_PTHREAD_H
5602 if (r->threads.sched.readyq_cnt > 0)
return;
5605 int sleeper_num = rb_ractor_sleeper_thread_num(r);
5606 int ltnum = rb_ractor_living_thread_num(r);
5608 if (ltnum > sleeper_num)
return;
5609 if (ltnum < sleeper_num) rb_bug(
"sleeper must not be more than vm_living_thread_num(vm)");
5614 ccan_list_for_each(&r->threads.set, th, lt_node) {
5615 if (th->status != THREAD_STOPPED_FOREVER || RUBY_VM_INTERRUPTED(th->ec)) {
5618 else if (th->locking_mutex) {
5619 rb_mutex_t *mutex = mutex_ptr(th->locking_mutex);
5620 if (mutex->fiber == th->ec->fiber_ptr || (!mutex->fiber && !ccan_list_empty(&mutex->waitq))) {
5631 argv[1] =
rb_str_new2(
"No live threads left. Deadlock?");
5632 debug_deadlock_check(r, argv[1]);
5633 rb_ractor_sleeper_threads_dec(GET_RACTOR());
5634 rb_threadptr_raise(r->threads.main, 2, argv);
5641rb_vm_memsize_waiting_fds(
struct ccan_list_head *waiting_fds)
5646 ccan_list_for_each(waiting_fds, waitfd, wfd_node) {
5657 VALUE coverage = rb_iseq_coverage(cfp->iseq);
5665 if (GET_VM()->coverage_mode & COVERAGE_TARGET_ONESHOT_LINES) {
5666 rb_iseq_clear_event_flags(cfp->iseq, cfp->pc - ISEQ_BODY(cfp->iseq)->iseq_encoded - 1, RUBY_EVENT_COVERAGE_LINE);
5667 rb_ary_push(lines,
LONG2FIX(line + 1));
5687 VALUE coverage = rb_iseq_coverage(cfp->iseq);
5691 long pc = cfp->pc - ISEQ_BODY(cfp->iseq)->iseq_encoded - 1;
5706 VALUE path, beg_pos_lineno, beg_pos_column, end_pos_lineno, end_pos_column;
5708 if (!me->def)
return NULL;
5711 switch (me->def->type) {
5712 case VM_METHOD_TYPE_ISEQ: {
5715 path = rb_iseq_path(iseq);
5716 beg_pos_lineno =
INT2FIX(loc->code_location.beg_pos.lineno);
5717 beg_pos_column =
INT2FIX(loc->code_location.beg_pos.column);
5718 end_pos_lineno =
INT2FIX(loc->code_location.end_pos.lineno);
5719 end_pos_column =
INT2FIX(loc->code_location.end_pos.column);
5722 case VM_METHOD_TYPE_BMETHOD: {
5723 const rb_iseq_t *iseq = rb_proc_get_iseq(me->def->body.bmethod.proc, 0);
5726 rb_iseq_check(iseq);
5727 path = rb_iseq_path(iseq);
5728 loc = &ISEQ_BODY(iseq)->location;
5729 beg_pos_lineno =
INT2FIX(loc->code_location.beg_pos.lineno);
5730 beg_pos_column =
INT2FIX(loc->code_location.beg_pos.column);
5731 end_pos_lineno =
INT2FIX(loc->code_location.end_pos.lineno);
5732 end_pos_column =
INT2FIX(loc->code_location.end_pos.column);
5737 case VM_METHOD_TYPE_ALIAS:
5738 me = me->def->body.alias.original_me;
5740 case VM_METHOD_TYPE_REFINED:
5741 me = me->def->body.refined.orig_me;
5742 if (!me)
return NULL;
5750 path = rb_ary_entry(path, 1);
5753 if (resolved_location) {
5754 resolved_location[0] = path;
5755 resolved_location[1] = beg_pos_lineno;
5756 resolved_location[2] = beg_pos_column;
5757 resolved_location[3] = end_pos_lineno;
5758 resolved_location[4] = end_pos_column;
5772 me = rb_resolve_me_location(me, 0);
5775 rcount = rb_hash_aref(me2counter, (
VALUE) me);
5783rb_get_coverages(
void)
5785 return GET_VM()->coverages;
5789rb_get_coverage_mode(
void)
5791 return GET_VM()->coverage_mode;
5795rb_set_coverages(
VALUE coverages,
int mode,
VALUE me2counter)
5797 GET_VM()->coverages = coverages;
5798 GET_VM()->me2counter = me2counter;
5799 GET_VM()->coverage_mode = mode;
5803rb_resume_coverages(
void)
5805 int mode = GET_VM()->coverage_mode;
5806 VALUE me2counter = GET_VM()->me2counter;
5807 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);
5808 if (mode & COVERAGE_TARGET_BRANCHES) {
5809 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);
5811 if (mode & COVERAGE_TARGET_METHODS) {
5817rb_suspend_coverages(
void)
5820 if (GET_VM()->coverage_mode & COVERAGE_TARGET_BRANCHES) {
5823 if (GET_VM()->coverage_mode & COVERAGE_TARGET_METHODS) {
5830rb_reset_coverages(
void)
5832 rb_clear_coverages();
5833 rb_iseq_remove_coverage_all();
5834 GET_VM()->coverages =
Qfalse;
5838rb_default_coverage(
int n)
5840 VALUE coverage = rb_ary_hidden_new_fill(3);
5842 int mode = GET_VM()->coverage_mode;
5844 if (mode & COVERAGE_TARGET_LINES) {
5845 lines = n > 0 ? rb_ary_hidden_new_fill(n) : rb_ary_hidden_new(0);
5847 RARRAY_ASET(coverage, COVERAGE_INDEX_LINES, lines);
5849 if (mode & COVERAGE_TARGET_BRANCHES) {
5850 branches = rb_ary_hidden_new_fill(2);
5872 VALUE structure = rb_hash_new();
5878 RARRAY_ASET(coverage, COVERAGE_INDEX_BRANCHES, branches);
5884uninterruptible_exit(
VALUE v)
5887 rb_ary_pop(cur_th->pending_interrupt_mask_stack);
5889 cur_th->pending_interrupt_queue_checked = 0;
5890 if (!rb_threadptr_pending_interrupt_empty_p(cur_th)) {
5891 RUBY_VM_SET_INTERRUPT(cur_th->ec);
5899 VALUE interrupt_mask = rb_ident_hash_new();
5902 rb_hash_aset(interrupt_mask, rb_cObject, sym_never);
5904 rb_ary_push(cur_th->pending_interrupt_mask_stack, interrupt_mask);
5908 RUBY_VM_CHECK_INTS(cur_th->ec);
5915 VM_ASSERT(th->specific_storage == NULL);
5917 if (UNLIKELY(specific_key_count > 0)) {
5918 th->specific_storage =
ZALLOC_N(
void *, RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX);
5922rb_internal_thread_specific_key_t
5927 if (specific_key_count == 0 && vm->ractor.cnt > 1) {
5928 rb_raise(
rb_eThreadError,
"The first rb_internal_thread_specific_key_create() is called with multiple ractors");
5930 else if (specific_key_count > RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX) {
5931 rb_raise(
rb_eThreadError,
"rb_internal_thread_specific_key_create() is called more than %d times", RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX);
5934 rb_internal_thread_specific_key_t key = specific_key_count++;
5941 ccan_list_for_each(&cr->threads.set, th, lt_node) {
5942 thread_specific_storage_alloc(th);
5955 VM_ASSERT(rb_thread_ptr(thread_val) == th);
5956 VM_ASSERT(key < RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX);
5957 VM_ASSERT(th->specific_storage);
5959 return th->specific_storage[key];
5968 VM_ASSERT(rb_thread_ptr(thread_val) == th);
5969 VM_ASSERT(key < RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX);
5970 VM_ASSERT(th->specific_storage);
5972 th->specific_storage[key] = data;
5978 struct ccan_list_node node;
5980 rb_interrupt_exec_func_t *func;
5982 enum rb_interrupt_exec_flag flags;
5986rb_threadptr_interrupt_exec_task_mark(
rb_thread_t *th)
5990 ccan_list_for_each(&th->interrupt_exec_tasks, task, node) {
5991 if (task->flags & rb_interrupt_exec_flag_value_data) {
5992 rb_gc_mark((
VALUE)task->data);
6000rb_threadptr_interrupt_exec(
rb_thread_t *th, rb_interrupt_exec_func_t *func,
void *data,
enum rb_interrupt_exec_flag flags)
6012 ccan_list_add_tail(&th->interrupt_exec_tasks, &task->node);
6013 threadptr_interrupt_locked(th,
true);
6031 (*task->func)(task->data);
6055 rb_interrupt_exec_func_t *func;
6060interrupt_ractor_new_thread_func(
void *data)
6070interrupt_ractor_func(
void *data)
6080 rb_interrupt_exec_func_t *func,
void *data,
enum rb_interrupt_exec_flag flags)
6087 rb_threadptr_interrupt_exec(main_th, interrupt_ractor_func, d, flags);
#define RUBY_ASSERT_ALWAYS(expr,...)
A variant of RUBY_ASSERT that does not interface with RUBY_DEBUG.
std::atomic< unsigned > rb_atomic_t
Type that is eligible for atomic operations.
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
#define RUBY_INTERNAL_EVENT_SWITCH
Thread switched.
int rb_remove_event_hook(rb_event_hook_func_t func)
Removes the passed function from the list of event hooks.
#define RUBY_EVENT_THREAD_BEGIN
Encountered a new thread.
void(* rb_event_hook_func_t)(rb_event_flag_t evflag, VALUE data, VALUE self, ID mid, VALUE klass)
Type of event hooks.
uint32_t rb_event_flag_t
Represents event(s).
#define RUBY_EVENT_CALL
A method, written in Ruby, is called.
#define RUBY_EVENT_THREAD_END
Encountered an end of a thread.
static void RB_FL_SET_RAW(VALUE obj, VALUE flags)
This is an implementation detail of RB_FL_SET().
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
ID rb_frame_last_func(void)
Returns the ID of the last method in the call stack.
int rb_keyword_given_p(void)
Determines if the current method is given a keyword argument.
int rb_block_given_p(void)
Determines if the current method is given a block.
#define rb_str_new2
Old name of rb_str_new_cstr.
#define ALLOC
Old name of RB_ALLOC.
#define T_STRING
Old name of RUBY_T_STRING.
#define xfree
Old name of ruby_xfree.
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
#define OBJ_FROZEN
Old name of RB_OBJ_FROZEN.
#define xrealloc
Old name of ruby_xrealloc.
#define ID2SYM
Old name of RB_ID2SYM.
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
#define CLASS_OF
Old name of rb_class_of.
#define xmalloc
Old name of ruby_xmalloc.
#define LONG2FIX
Old name of RB_INT2FIX.
#define FIX2INT
Old name of RB_FIX2INT.
#define ZALLOC_N
Old name of RB_ZALLOC_N.
#define T_ICLASS
Old name of RUBY_T_ICLASS.
#define T_HASH
Old name of RUBY_T_HASH.
#define Qtrue
Old name of RUBY_Qtrue.
#define NUM2INT
Old name of RB_NUM2INT.
#define INT2NUM
Old name of RB_INT2NUM.
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define FIX2LONG
Old name of RB_FIX2LONG.
#define T_ARRAY
Old name of RUBY_T_ARRAY.
#define T_OBJECT
Old name of RUBY_T_OBJECT.
#define NIL_P
Old name of RB_NIL_P.
#define POSFIXABLE
Old name of RB_POSFIXABLE.
#define BUILTIN_TYPE
Old name of RB_BUILTIN_TYPE.
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define SYMBOL_P
Old name of RB_SYMBOL_P.
void ruby_stop(int ex)
Calls ruby_cleanup() and exits the process.
#define ruby_debug
This variable controls whether the interpreter is in debug mode.
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
VALUE rb_eSystemExit
SystemExit exception.
VALUE rb_eIOError
IOError exception.
VALUE rb_eStandardError
StandardError exception.
VALUE rb_eTypeError
TypeError exception.
void rb_frozen_error_raise(VALUE frozen_obj, const char *fmt,...)
Raises an instance of rb_eFrozenError.
VALUE rb_eFatal
fatal exception.
VALUE rb_eRuntimeError
RuntimeError exception.
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
VALUE rb_exc_new(VALUE etype, const char *ptr, long len)
Creates an instance of the passed exception class.
VALUE rb_eException
Mother of all exceptions.
VALUE rb_eThreadError
ThreadError exception.
void rb_exit(int status)
Terminates the current execution context.
VALUE rb_eSignal
SignalException exception.
VALUE rb_obj_alloc(VALUE klass)
Allocates an instance of the given class.
VALUE rb_cInteger
Module class.
VALUE rb_obj_hide(VALUE obj)
Make the object invisible from Ruby code.
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
VALUE rb_cThread
Thread class.
VALUE rb_cModule
Module class.
double rb_num2dbl(VALUE num)
Converts an instance of rb_cNumeric into C's double.
VALUE rb_obj_is_kind_of(VALUE obj, VALUE klass)
Queries if the given object is an instance (of possibly descendants) of the given class.
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
VALUE rb_block_proc(void)
Constructs a Proc object from implicitly passed components.
void rb_reset_random_seed(void)
Resets the RNG behind rb_genrand_int32()/rb_genrand_real().
VALUE rb_str_new_frozen(VALUE str)
Creates a frozen copy of the string, if necessary.
VALUE rb_str_concat(VALUE dst, VALUE src)
Identical to rb_str_append(), except it also accepts an integer as a codepoint.
#define rb_str_cat_cstr(buf, str)
Identical to rb_str_cat(), except it assumes the passed pointer is a pointer to a C string.
#define rb_str_new_cstr(str)
Identical to rb_str_new, except it assumes the passed pointer is a pointer to a C string.
int rb_thread_interrupted(VALUE thval)
Checks if the thread's execution was recently interrupted.
VALUE rb_thread_local_aref(VALUE thread, ID key)
This badly named function reads from a Fiber local storage.
VALUE rb_mutex_new(void)
Creates a mutex.
VALUE rb_thread_kill(VALUE thread)
Terminates the given thread.
#define RUBY_UBF_IO
A special UBF for blocking IO operations.
VALUE rb_thread_main(void)
Obtains the "main" thread.
VALUE rb_exec_recursive(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE h)
"Recursion" API entry point.
void rb_thread_sleep_forever(void)
Blocks indefinitely.
void rb_thread_fd_close(int fd)
Notifies a closing of a file descriptor to other threads.
void rb_thread_wait_for(struct timeval time)
Identical to rb_thread_sleep(), except it takes struct timeval instead.
VALUE rb_thread_stop(void)
Stops the current thread.
VALUE rb_mutex_sleep(VALUE self, VALUE timeout)
Releases the lock held in the mutex and waits for the period of time; reacquires the lock on wakeup.
VALUE rb_exec_recursive_paired(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE p, VALUE h)
Identical to rb_exec_recursive(), except it checks for the recursion on the ordered pair of { g,...
void rb_unblock_function_t(void *)
This is the type of UBFs.
void rb_thread_atfork_before_exec(void)
:FIXME: situation of this function is unclear.
void rb_thread_check_ints(void)
Checks for interrupts.
VALUE rb_thread_run(VALUE thread)
This is a rb_thread_wakeup() + rb_thread_schedule() combo.
VALUE rb_thread_wakeup(VALUE thread)
Marks a given thread as eligible for scheduling.
VALUE rb_mutex_unlock(VALUE mutex)
Releases the mutex.
VALUE rb_exec_recursive_paired_outer(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE p, VALUE h)
Identical to rb_exec_recursive_outer(), except it checks for the recursion on the ordered pair of { g...
void rb_thread_sleep_deadly(void)
Identical to rb_thread_sleep_forever(), except the thread calling this function is considered "dead" ...
void rb_thread_atfork(void)
A pthread_atfork(3posix)-like API.
VALUE rb_thread_current(void)
Obtains the "current" thread.
int rb_thread_alone(void)
Checks if the thread this function is running is the only thread that is currently alive.
VALUE rb_thread_local_aset(VALUE thread, ID key, VALUE val)
This badly named function writes to a Fiber local storage.
void rb_thread_schedule(void)
Tries to switch to another thread.
#define RUBY_UBF_PROCESS
A special UBF for blocking process operations.
VALUE rb_exec_recursive_outer(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE h)
Identical to rb_exec_recursive(), except it calls f for outermost recursion only.
VALUE rb_thread_wakeup_alive(VALUE thread)
Identical to rb_thread_wakeup(), except it doesn't raise on an already killed thread.
VALUE rb_mutex_lock(VALUE mutex)
Attempts to lock the mutex.
void rb_thread_sleep(int sec)
Blocks for the given period of time.
void rb_timespec_now(struct timespec *ts)
Fills the current time into the given struct.
struct timeval rb_time_timeval(VALUE time)
Converts an instance of rb_cTime to a struct timeval that represents the identical point of time.
VALUE rb_ivar_set(VALUE obj, ID name, VALUE val)
Identical to rb_iv_set(), except it accepts the name as an ID instead of a C string.
VALUE rb_ivar_get(VALUE obj, ID name)
Identical to rb_iv_get(), except it accepts the name as an ID instead of a C string.
VALUE rb_class_path(VALUE mod)
Identical to rb_mod_name(), except it returns #<Class: ...> style inspection for anonymous modules.
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
int rb_sourceline(void)
Resembles __LINE__.
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
ID rb_check_id(volatile VALUE *namep)
Detects if the given name is already interned or not.
VALUE rb_to_symbol(VALUE name)
Identical to rb_intern_str(), except it generates a dynamic symbol if necessary.
VALUE rb_eIOTimeoutError
Indicates that a timeout has occurred while performing an IO operation.
#define RB_NOGVL_UBF_ASYNC_SAFE
Passing this flag to rb_nogvl() indicates that the passed UBF is async-signal-safe.
void * rb_internal_thread_specific_get(VALUE thread_val, rb_internal_thread_specific_key_t key)
Get thread and tool specific data.
#define RB_NOGVL_INTR_FAIL
Passing this flag to rb_nogvl() prevents it from checking interrupts.
void rb_internal_thread_specific_set(VALUE thread_val, rb_internal_thread_specific_key_t key, void *data)
Set thread and tool specific data.
rb_internal_thread_specific_key_t rb_internal_thread_specific_key_create(void)
Create a key to store thread specific data.
void * rb_nogvl(void *(*func)(void *), void *data1, rb_unblock_function_t *ubf, void *data2, int flags)
Identical to rb_thread_call_without_gvl(), except it additionally takes "flags" that change the behav...
void * rb_thread_call_with_gvl(void *(*func)(void *), void *data1)
(Re-)acquires the GVL.
#define RB_NOGVL_OFFLOAD_SAFE
Passing this flag to rb_nogvl() indicates that the passed function is safe to offload to a background...
void * rb_thread_call_without_gvl2(void *(*func)(void *), void *data1, rb_unblock_function_t *ubf, void *data2)
Identical to rb_thread_call_without_gvl(), except it does not interface with signals etc.
void * rb_thread_call_without_gvl(void *(*func)(void *), void *data1, rb_unblock_function_t *ubf, void *data2)
Allows the passed function to run in parallel with other Ruby threads.
#define RB_BLOCK_CALL_FUNC_ARGLIST(yielded_arg, callback_arg)
Shim for block function parameters.
VALUE rb_yield(VALUE val)
Yields the block.
void rb_throw_obj(VALUE tag, VALUE val)
Identical to rb_throw(), except it allows arbitrary Ruby object to become a tag.
static int rb_fd_max(const rb_fdset_t *f)
It seems this function has no use.
void rb_fd_copy(rb_fdset_t *dst, const fd_set *src, int max)
Destructively overwrites an fdset with another.
void rb_fd_dup(rb_fdset_t *dst, const rb_fdset_t *src)
Identical to rb_fd_copy(), except it copies unlimited number of file descriptors.
void rb_fd_term(rb_fdset_t *f)
Destroys the rb_fdset_t, releasing any memory and resources it used.
static fd_set * rb_fd_ptr(const rb_fdset_t *f)
Raw pointer to fd_set.
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
#define ALLOCA_N(type, n)
#define MEMZERO(p, type, n)
Handy macro to erase a region of memory.
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
VALUE rb_thread_create(type *q, void *w)
Creates a rb_cThread instance.
void rb_hash_foreach(VALUE q, int_type *w, VALUE e)
Iteration over the given hash.
VALUE rb_ensure(type *q, VALUE w, type *e, VALUE r)
An equivalent of ensure clause.
#define rb_fd_isset
Queries if the given fd is in the rb_fdset_t.
#define rb_fd_select
Waits for multiple file descriptors at once.
#define rb_fd_init
Initialises the :given :rb_fdset_t.
#define rb_fd_set
Sets the given fd to the rb_fdset_t.
#define rb_fd_zero
Clears the given rb_fdset_t.
#define rb_fd_clr
Unsets the given fd from the rb_fdset_t.
#define RARRAY_LEN
Just another name of rb_array_len.
static int RARRAY_LENINT(VALUE ary)
Identical to rb_array_len(), except it differs for the return type.
static void RARRAY_ASET(VALUE ary, long i, VALUE v)
Assigns an object in an array.
#define RARRAY_AREF(a, i)
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
static VALUE RBASIC_CLASS(VALUE obj)
Queries the class of an object.
#define RBASIC(obj)
Convenient casting macro.
#define RCLASS_SUPER
Just another name of rb_class_get_superclass.
#define DATA_PTR(obj)
Convenient getter macro.
#define RHASH_EMPTY_P(h)
Checks if the hash is empty.
#define StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
#define RUBY_TYPED_DEFAULT_FREE
This is a value you can set to rb_data_type_struct::dfree.
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
#define TypedData_Wrap_Struct(klass, data_type, sval)
Converts sval, a pointer to your struct, into a Ruby object.
#define TypedData_Make_Struct(klass, type, data_type, sval)
Identical to TypedData_Wrap_Struct, except it allocates a new data region internally instead of takin...
#define errno
Ractor-aware version of errno.
int ruby_native_thread_p(void)
Queries if the thread which calls this function is a ruby's thread.
int ruby_snprintf(char *str, size_t n, char const *fmt,...)
Our own locale-insensitive version of snprintf(3).
#define RB_PASS_CALLED_KEYWORDS
Pass keywords if current method is called with keywords, useful for argument delegation.
VALUE rb_fiber_scheduler_blocking_operation_wait(VALUE scheduler, void *(*function)(void *), void *data, rb_unblock_function_t *unblock_function, void *data2, int flags, struct rb_fiber_scheduler_blocking_operation_state *state)
Defer the execution of the passed function to the scheduler.
VALUE rb_fiber_scheduler_current(void)
Identical to rb_fiber_scheduler_get(), except it also returns RUBY_Qnil in case of a blocking fiber.
VALUE rb_fiber_scheduler_block(VALUE scheduler, VALUE blocker, VALUE timeout)
Non-blocking wait for the passed "blocker", which is for instance Thread.join or Mutex....
VALUE rb_fiber_scheduler_set(VALUE scheduler)
Destructively assigns the passed scheduler to that of the current thread that is calling this functio...
VALUE rb_fiber_scheduler_unblock(VALUE scheduler, VALUE blocker, VALUE fiber)
Wakes up a fiber previously blocked using rb_fiber_scheduler_block().
int rb_thread_fd_select(int nfds, rb_fdset_t *rfds, rb_fdset_t *wfds, rb_fdset_t *efds, struct timeval *timeout)
Waits for multiple file descriptors at once.
#define rb_fd_resize(n, f)
Does nothing (defined for compatibility).
static bool RB_TEST(VALUE obj)
Emulates Ruby's "if" statement.
#define RTEST
This is an old name of RB_TEST.
#define _(args)
This was a transition path from K&R to ANSI.
This is the struct that holds necessary info for a struct.
The data structure which wraps the fd_set bitmap used by select(2).
int maxfd
Maximum allowed number of FDs.
fd_set * fdset
File descriptors buffer.
int capa
Maximum allowed number of FDs.
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.