60 #undef _FORTIFY_SOURCE
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"
99 #include "ractor_core.h"
100 #include "vm_debug.h"
103 #if USE_RJIT && defined(HAVE_SYS_WAIT_H)
104 #include <sys/wait.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
113 static VALUE rb_cThreadShield;
115 static VALUE sym_immediate;
116 static VALUE sym_on_blocking;
117 static VALUE sym_never;
119 #define THREAD_LOCAL_STORAGE_INITIALISED FL_USER13
120 #define THREAD_LOCAL_STORAGE_INITIALISED_P(th) RB_FL_TEST_RAW((th), THREAD_LOCAL_STORAGE_INITIALISED)
123 rb_thread_local_storage(
VALUE thread)
125 if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
133 SLEEP_DEADLOCKABLE = 0x01,
134 SLEEP_SPURIOUS_CHECK = 0x02,
135 SLEEP_ALLOW_SPURIOUS = 0x04,
136 SLEEP_NO_CHECKINTS = 0x08,
139 static void sleep_forever(
rb_thread_t *th,
unsigned int fl);
140 static int sleep_hrtime(
rb_thread_t *, rb_hrtime_t,
unsigned int fl);
142 static void rb_thread_sleep_deadly_allow_spurious_wakeup(
VALUE blocker,
VALUE timeout, rb_hrtime_t end);
145 static int rb_threadptr_pending_interrupt_empty_p(
const rb_thread_t *th);
146 static const char *thread_status_name(
rb_thread_t *th,
int detail);
147 static int hrtime_update_expire(rb_hrtime_t *,
const rb_hrtime_t);
148 NORETURN(
static void async_bug_fd(
const char *mesg,
int errno_arg,
int fd));
149 MAYBE_UNUSED(
static int consume_communication_pipe(
int fd));
151 static volatile int system_working = 1;
152 static rb_internal_thread_specific_key_t specific_key_count;
155 struct ccan_list_node wfd_node;
163 #define THREAD_SYSTEM_DEPENDENT_IMPLEMENTATION
166 enum rb_thread_status prev_status;
170 static void unblock_function_clear(
rb_thread_t *th);
176 #define THREAD_BLOCKING_BEGIN(th) do { \
177 struct rb_thread_sched * const sched = TH_SCHED(th); \
178 RB_VM_SAVE_MACHINE_CONTEXT(th); \
179 thread_sched_to_waiting((sched), (th));
181 #define THREAD_BLOCKING_END(th) \
182 thread_sched_to_running((sched), (th)); \
183 rb_ractor_thread_switch(th->ractor, th); \
187 #ifdef HAVE_BUILTIN___BUILTIN_CHOOSE_EXPR_CONSTANT_P
188 #define only_if_constant(expr, notconst) __builtin_choose_expr(__builtin_constant_p(expr), (expr), (notconst))
190 #define only_if_constant(expr, notconst) (__builtin_constant_p(expr) ? (expr) : (notconst))
193 #define only_if_constant(expr, notconst) notconst
195 #define BLOCKING_REGION(th, exec, ubf, ubfarg, fail_if_interrupted) do { \
196 struct rb_blocking_region_buffer __region; \
197 if (blocking_region_begin(th, &__region, (ubf), (ubfarg), fail_if_interrupted) || \
199 !only_if_constant(fail_if_interrupted, TRUE)) { \
202 RB_VM_SAVE_MACHINE_CONTEXT(th); \
203 thread_sched_to_waiting(TH_SCHED(th), th); \
205 blocking_region_end(th, &__region); \
213 #define RUBY_VM_CHECK_INTS_BLOCKING(ec) vm_check_ints_blocking(ec)
219 if (LIKELY(rb_threadptr_pending_interrupt_empty_p(th))) {
220 if (LIKELY(!RUBY_VM_INTERRUPTED_ANY(ec)))
return FALSE;
223 th->pending_interrupt_queue_checked = 0;
224 RUBY_VM_SET_INTERRUPT(ec);
226 return rb_threadptr_execute_interrupts(th, 1);
232 return vm_check_ints_blocking(ec);
240 #if defined(HAVE_POLL)
241 # if defined(__linux__)
244 # if defined(__FreeBSD_version) && __FreeBSD_version >= 1100000
247 # define POLLERR_SET (POLLHUP | POLLERR)
252 timeout_prepare(rb_hrtime_t **to, rb_hrtime_t *rel, rb_hrtime_t *end,
256 *rel = rb_timeval2hrtime(timeout);
257 *end = rb_hrtime_add(rb_hrtime_now(), *rel);
265 MAYBE_UNUSED(NOINLINE(
static int thread_start_func_2(
rb_thread_t *th,
VALUE *stack_start)));
266 MAYBE_UNUSED(
static bool th_has_dedicated_nt(
const rb_thread_t *th));
267 MAYBE_UNUSED(
static int waitfd_to_waiting_flag(
int wfd_event));
269 #include THREAD_IMPL_SRC
276 #ifndef BUSY_WAIT_SIGNALS
277 # define BUSY_WAIT_SIGNALS (0)
281 # define USE_EVENTFD (0)
284 #include "thread_sync.c"
314 if (fail_if_interrupted) {
315 if (RUBY_VM_INTERRUPTED_ANY(th->ec)) {
320 RUBY_VM_CHECK_INTS(th->ec);
324 }
while (!th->ec->raised_flag && RUBY_VM_INTERRUPTED_ANY(th->ec) &&
327 VM_ASSERT(th->unblock.func == NULL);
329 th->unblock.func = func;
330 th->unblock.arg = arg;
340 th->unblock.func = 0;
345 threadptr_interrupt_locked(
rb_thread_t *th,
bool trap)
349 RUBY_DEBUG_LOG(
"th:%u trap:%d", rb_th_serial(th), trap);
352 RUBY_VM_SET_TRAP_INTERRUPT(th->ec);
355 RUBY_VM_SET_INTERRUPT(th->ec);
358 if (th->unblock.func != NULL) {
359 (th->unblock.func)(th->unblock.arg);
371 threadptr_interrupt_locked(th, trap);
379 RUBY_DEBUG_LOG(
"th:%u", rb_th_serial(th));
380 threadptr_interrupt(th,
false);
386 threadptr_interrupt(th,
true);
394 ccan_list_for_each(&r->threads.set, th, lt_node) {
395 if (th != main_thread) {
396 RUBY_DEBUG_LOG(
"terminate start th:%u status:%s", rb_th_serial(th), thread_status_name(th, TRUE));
398 rb_threadptr_pending_interrupt_enque(th, RUBY_FATAL_THREAD_TERMINATED);
399 rb_threadptr_interrupt(th);
401 RUBY_DEBUG_LOG(
"terminate done th:%u status:%s", rb_th_serial(th), thread_status_name(th, TRUE));
404 RUBY_DEBUG_LOG(
"main thread th:%u", rb_th_serial(th));
412 while (thread->join_list) {
416 thread->join_list = join_list->next;
420 if (target_thread->scheduler !=
Qnil && join_list->fiber) {
424 rb_threadptr_interrupt(target_thread);
426 switch (target_thread->status) {
428 case THREAD_STOPPED_FOREVER:
429 target_thread->status = THREAD_RUNNABLE;
439 rb_threadptr_unlock_all_locking_mutexes(
rb_thread_t *th)
441 while (th->keeping_mutexes) {
443 th->keeping_mutexes = mutex->next_mutex;
447 const char *error_message = rb_mutex_unlock_th(mutex, th, mutex->fiber);
448 if (error_message)
rb_bug(
"invalid keeping_mutexes: %s", error_message);
457 volatile int sleeping = 0;
459 if (cr->threads.main != th) {
460 rb_bug(
"rb_thread_terminate_all: called by child thread (%p, %p)",
461 (
void *)cr->threads.main, (
void *)th);
465 rb_threadptr_unlock_all_locking_mutexes(th);
468 if (EC_EXEC_TAG() == TAG_NONE) {
470 RUBY_DEBUG_LOG(
"th:%u", rb_th_serial(th));
472 terminate_all(cr, th);
474 while (rb_ractor_living_thread_num(cr) > 1) {
475 rb_hrtime_t rel = RB_HRTIME_PER_SEC;
481 native_sleep(th, &rel);
482 RUBY_VM_CHECK_INTS_BLOCKING(ec);
500 void rb_threadptr_root_fiber_terminate(
rb_thread_t *th);
501 static void threadptr_interrupt_exec_cleanup(
rb_thread_t *th);
504 thread_cleanup_func_before_exec(
void *th_ptr)
507 th->status = THREAD_KILLED;
510 th->ec->machine.stack_start = th->ec->machine.stack_end = NULL;
512 threadptr_interrupt_exec_cleanup(th);
513 rb_threadptr_root_fiber_terminate(th);
517 thread_cleanup_func(
void *th_ptr,
int atfork)
521 th->locking_mutex =
Qfalse;
522 thread_cleanup_func_before_exec(th_ptr);
541 ruby_thread_init_stack(
rb_thread_t *th,
void *local_in_parent_frame)
543 native_thread_init_stack(th, local_in_parent_frame);
547 rb_vm_proc_local_ep(
VALUE proc)
549 const VALUE *ep = vm_proc_ep(proc);
552 return rb_vm_ep_local_ep(ep);
561 int argc,
const VALUE *argv,
int kw_splat,
VALUE passed_block_handler);
566 VALUE args = th->invoke_arg.proc.args;
567 const VALUE *args_ptr;
569 VALUE procval = th->invoke_arg.proc.proc;
571 GetProcPtr(procval, proc);
573 th->ec->errinfo =
Qnil;
574 th->ec->root_lep = rb_vm_proc_local_ep(procval);
575 th->ec->root_svar =
Qfalse;
577 vm_check_ints_blocking(th->ec);
579 if (th->invoke_type == thread_invoke_type_ractor_proc) {
580 VALUE self = rb_ractor_self(th->ractor);
584 rb_ractor_receive_parameters(th->ec, th->ractor, args_len, (
VALUE *)args_ptr);
585 vm_check_ints_blocking(th->ec);
587 return rb_vm_invoke_proc_with_self(
590 th->invoke_arg.proc.kw_splat,
591 VM_BLOCK_HANDLER_NONE
600 th->invoke_arg.proc.args =
Qnil;
606 vm_check_ints_blocking(th->ec);
608 return rb_vm_invoke_proc(
611 th->invoke_arg.proc.kw_splat,
612 VM_BLOCK_HANDLER_NONE
620 native_set_thread_name(th);
623 switch (th->invoke_type) {
624 case thread_invoke_type_proc:
625 result = thread_do_start_proc(th);
628 case thread_invoke_type_ractor_proc:
629 result = thread_do_start_proc(th);
630 rb_ractor_atexit(th->ec, result);
633 case thread_invoke_type_func:
634 result = (*th->invoke_arg.func.func)(th->invoke_arg.func.arg);
637 case thread_invoke_type_none:
649 RUBY_DEBUG_LOG(
"th:%u", rb_th_serial(th));
650 VM_ASSERT(th != th->vm->ractor.main_thread);
652 enum ruby_tag_type state;
654 rb_thread_t *ractor_main_th = th->ractor->threads.main;
657 if (rb_ractor_status_p(th->ractor, ractor_blocking)) {
660 rb_vm_ractor_blocking_cnt_dec(th->vm, th->ractor, __FILE__, __LINE__);
662 r->r_stdin = rb_io_prep_stdin();
663 r->r_stdout = rb_io_prep_stdout();
664 r->r_stderr = rb_io_prep_stderr();
670 VM_ASSERT(UNDEF_P(th->value));
672 int fiber_scheduler_closed = 0, event_thread_end_hooked = 0;
677 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
680 result = thread_do_start(th);
683 if (!fiber_scheduler_closed) {
684 fiber_scheduler_closed = 1;
688 if (!event_thread_end_hooked) {
689 event_thread_end_hooked = 1;
693 if (state == TAG_NONE) {
697 errinfo = th->ec->errinfo;
699 VALUE exc = rb_vm_make_jump_tag_but_local_jump(state,
Qundef);
700 if (!
NIL_P(exc)) errinfo = exc;
702 if (state == TAG_FATAL) {
703 if (th->invoke_type == thread_invoke_type_ractor_proc) {
704 rb_ractor_atexit(th->ec,
Qnil);
712 if (th->report_on_exception) {
713 VALUE mesg = rb_thread_to_s(th->self);
714 rb_str_cat_cstr(mesg,
" terminated with exception (report_on_exception is true):\n");
715 rb_write_error_str(mesg);
716 rb_ec_error_print(th->ec, errinfo);
719 if (th->invoke_type == thread_invoke_type_ractor_proc) {
720 rb_ractor_atexit_exception(th->ec);
723 if (th->vm->thread_abort_on_exception ||
735 VM_ASSERT(!UNDEF_P(th->value));
737 rb_threadptr_join_list_wakeup(th);
738 rb_threadptr_unlock_all_locking_mutexes(th);
740 if (th->invoke_type == thread_invoke_type_ractor_proc) {
741 rb_thread_terminate_all(th);
742 rb_ractor_teardown(th->ec);
745 th->status = THREAD_KILLED;
746 RUBY_DEBUG_LOG(
"killed th:%u", rb_th_serial(th));
748 if (th->vm->ractor.main_thread == th) {
754 rb_threadptr_raise(ractor_main_th, 1, &errinfo);
759 rb_ec_clear_current_thread_trace_func(th->ec);
762 if (th->locking_mutex !=
Qfalse) {
763 rb_bug(
"thread_start_func_2: locking_mutex must not be set (%p:%"PRIxVALUE
")",
764 (
void *)th, th->locking_mutex);
767 if (ractor_main_th->status == THREAD_KILLED &&
768 th->ractor->threads.cnt <= 2 ) {
770 rb_threadptr_interrupt(ractor_main_th);
773 rb_check_deadlock(th->ractor);
775 rb_fiber_close(th->ec->fiber_ptr);
777 thread_cleanup_func(th, FALSE);
778 VM_ASSERT(th->ec->vm_stack == NULL);
780 if (th->invoke_type == thread_invoke_type_ractor_proc) {
784 thread_sched_to_dead(TH_SCHED(th), th);
785 rb_ractor_living_threads_remove(th->ractor, th);
788 rb_ractor_living_threads_remove(th->ractor, th);
789 thread_sched_to_dead(TH_SCHED(th), th);
796 enum thread_invoke_type type;
809 static void thread_specific_storage_alloc(
rb_thread_t *th);
815 rb_thread_t *th = rb_thread_ptr(thval), *current_th = rb_ec_thread_ptr(ec);
818 thread_specific_storage_alloc(th);
822 "can't start a new thread (frozen ThreadGroup)");
825 rb_fiber_inherit_storage(ec, th->ec->fiber_ptr);
827 switch (params->type) {
828 case thread_invoke_type_proc:
829 th->invoke_type = thread_invoke_type_proc;
830 th->invoke_arg.proc.args = params->args;
831 th->invoke_arg.proc.proc = params->proc;
835 case thread_invoke_type_ractor_proc:
836 #if RACTOR_CHECK_MODE > 0
837 rb_ractor_setup_belonging_to(thval, rb_ractor_id(params->g));
839 th->invoke_type = thread_invoke_type_ractor_proc;
840 th->ractor = params->g;
841 th->ractor->threads.main = th;
842 th->invoke_arg.proc.proc = rb_proc_isolate_bang(params->proc);
845 rb_ractor_send_parameters(ec, params->g, params->args);
848 case thread_invoke_type_func:
849 th->invoke_type = thread_invoke_type_func;
850 th->invoke_arg.func.func = params->fn;
851 th->invoke_arg.func.arg = (
void *)params->args;
858 th->priority = current_th->priority;
859 th->thgroup = current_th->thgroup;
862 th->pending_interrupt_queue_checked = 0;
863 th->pending_interrupt_mask_stack =
rb_ary_dup(current_th->pending_interrupt_mask_stack);
864 RBASIC_CLEAR_CLASS(th->pending_interrupt_mask_stack);
868 RUBY_DEBUG_LOG(
"r:%u th:%u", rb_ractor_id(th->ractor), rb_th_serial(th));
870 rb_ractor_living_threads_insert(th->ractor, th);
873 err = native_thread_create(th);
875 th->status = THREAD_KILLED;
876 rb_ractor_living_threads_remove(th->ractor, th);
882 #define threadptr_initialized(th) ((th)->invoke_type != thread_invoke_type_none)
905 thread_s_new(
int argc,
VALUE *argv,
VALUE klass)
908 VALUE thread = rb_thread_alloc(klass);
910 if (GET_RACTOR()->threads.main->status == THREAD_KILLED) {
915 th = rb_thread_ptr(thread);
916 if (!threadptr_initialized(th)) {
937 .type = thread_invoke_type_proc,
941 return thread_create_core(rb_thread_alloc(klass), ¶ms);
947 if (th->invoke_type == thread_invoke_type_proc) {
948 return rb_proc_location(th->invoke_arg.proc.proc);
964 else if (th->invoke_type != thread_invoke_type_none) {
965 VALUE loc = threadptr_invoke_proc_location(th);
968 "already initialized thread - %"PRIsVALUE
":%"PRIsVALUE,
977 .type = thread_invoke_type_proc,
981 return thread_create_core(thread, ¶ms);
989 .type = thread_invoke_type_func,
993 return thread_create_core(rb_thread_alloc(
rb_cThread), ¶ms);
1000 .type = thread_invoke_type_ractor_proc,
1005 return thread_create_core(rb_thread_alloc(
rb_cThread), ¶ms);
1017 remove_from_join_list(
VALUE arg)
1022 if (target_thread->status != THREAD_KILLED) {
1025 while (*join_list) {
1026 if (*join_list == p->waiter) {
1027 *join_list = (*join_list)->next;
1031 join_list = &(*join_list)->next;
1041 return th->status == THREAD_KILLED || !UNDEF_P(th->value);
1045 thread_join_sleep(
VALUE arg)
1048 rb_thread_t *target_th = p->target, *th = p->waiter->thread;
1049 rb_hrtime_t end = 0, *limit = p->limit;
1052 end = rb_hrtime_add(*limit, rb_hrtime_now());
1055 while (!thread_finished(target_th)) {
1058 if (scheduler !=
Qnil) {
1061 if (thread_finished(target_th))
break;
1066 sleep_forever(th, SLEEP_DEADLOCKABLE | SLEEP_ALLOW_SPURIOUS | SLEEP_NO_CHECKINTS);
1069 if (hrtime_update_expire(limit, end)) {
1070 RUBY_DEBUG_LOG(
"timeout target_th:%u", rb_th_serial(target_th));
1073 th->status = THREAD_STOPPED;
1074 native_sleep(th, limit);
1076 RUBY_VM_CHECK_INTS_BLOCKING(th->ec);
1077 th->status = THREAD_RUNNABLE;
1079 RUBY_DEBUG_LOG(
"interrupted target_th:%u status:%s", rb_th_serial(target_th), thread_status_name(target_th, TRUE));
1092 if (th == target_th) {
1096 if (th->ractor->threads.main == target_th) {
1100 RUBY_DEBUG_LOG(
"target_th:%u status:%s", rb_th_serial(target_th), thread_status_name(target_th, TRUE));
1102 if (target_th->status != THREAD_KILLED) {
1104 waiter.next = target_th->join_list;
1106 waiter.fiber = rb_fiberptr_blocking(fiber) ? NULL : fiber;
1107 target_th->join_list = &waiter;
1110 arg.waiter = &waiter;
1111 arg.target = target_th;
1112 arg.timeout = timeout;
1120 RUBY_DEBUG_LOG(
"success target_th:%u status:%s", rb_th_serial(target_th), thread_status_name(target_th, TRUE));
1122 if (target_th->ec->errinfo !=
Qnil) {
1123 VALUE err = target_th->ec->errinfo;
1128 RUBY_DEBUG_LOG(
"terminated target_th:%u status:%s", rb_th_serial(target_th), thread_status_name(target_th, TRUE));
1133 rb_bug(
"thread_join: Fixnum (%d) should not reach here.",
FIX2INT(err));
1136 else if (THROW_DATA_P(target_th->ec->errinfo)) {
1137 rb_bug(
"thread_join: THROW_DATA should not reach here.");
1144 return target_th->self;
1187 thread_join_m(
int argc,
VALUE *argv,
VALUE self)
1190 rb_hrtime_t rel = 0, *limit = 0;
1201 if (
NIL_P(timeout)) {
1205 rel = rb_sec2hrtime(NUM2TIMET(timeout));
1209 limit = double2hrtime(&rel,
rb_num2dbl(timeout));
1212 return thread_join(rb_thread_ptr(
self), timeout, limit);
1230 thread_value(
VALUE self)
1233 thread_join(th,
Qnil, 0);
1234 if (UNDEF_P(th->value)) {
1248 #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
1249 if (clock_gettime(CLOCK_MONOTONIC, ts) == 0)
1259 NOINLINE(rb_hrtime_t rb_hrtime_now(
void));
1266 return rb_timespec2hrtime(&ts);
1273 COMPILER_WARNING_PUSH
1274 #if defined(__GNUC__) && __GNUC__ == 7 && __GNUC_MINOR__ <= 3
1275 COMPILER_WARNING_IGNORED(-Wmaybe-uninitialized)
1278 #define PRIu64 PRI_64_PREFIX "u"
1286 hrtime_update_expire(rb_hrtime_t *timeout,
const rb_hrtime_t end)
1288 rb_hrtime_t now = rb_hrtime_now();
1290 if (now > end)
return 1;
1292 RUBY_DEBUG_LOG(
"%"PRIu64
" > %"PRIu64
"", (uint64_t)end, (uint64_t)now);
1294 *timeout = end - now;
1297 COMPILER_WARNING_POP
1300 sleep_hrtime(
rb_thread_t *th, rb_hrtime_t rel,
unsigned int fl)
1302 enum rb_thread_status prev_status = th->status;
1304 rb_hrtime_t end = rb_hrtime_add(rb_hrtime_now(), rel);
1306 th->status = THREAD_STOPPED;
1307 RUBY_VM_CHECK_INTS_BLOCKING(th->ec);
1308 while (th->status == THREAD_STOPPED) {
1309 native_sleep(th, &rel);
1310 woke = vm_check_ints_blocking(th->ec);
1311 if (woke && !(fl & SLEEP_SPURIOUS_CHECK))
1313 if (hrtime_update_expire(&rel, end))
1317 th->status = prev_status;
1322 sleep_hrtime_until(
rb_thread_t *th, rb_hrtime_t end,
unsigned int fl)
1324 enum rb_thread_status prev_status = th->status;
1326 rb_hrtime_t rel = rb_hrtime_sub(end, rb_hrtime_now());
1328 th->status = THREAD_STOPPED;
1329 RUBY_VM_CHECK_INTS_BLOCKING(th->ec);
1330 while (th->status == THREAD_STOPPED) {
1331 native_sleep(th, &rel);
1332 woke = vm_check_ints_blocking(th->ec);
1333 if (woke && !(fl & SLEEP_SPURIOUS_CHECK))
1335 if (hrtime_update_expire(&rel, end))
1339 th->status = prev_status;
1346 enum rb_thread_status prev_status = th->status;
1347 enum rb_thread_status status;
1350 status = fl & SLEEP_DEADLOCKABLE ? THREAD_STOPPED_FOREVER : THREAD_STOPPED;
1351 th->status = status;
1353 if (!(fl & SLEEP_NO_CHECKINTS)) RUBY_VM_CHECK_INTS_BLOCKING(th->ec);
1355 while (th->status == status) {
1356 if (fl & SLEEP_DEADLOCKABLE) {
1357 rb_ractor_sleeper_threads_inc(th->ractor);
1358 rb_check_deadlock(th->ractor);
1361 native_sleep(th, 0);
1363 if (fl & SLEEP_DEADLOCKABLE) {
1364 rb_ractor_sleeper_threads_dec(th->ractor);
1366 if (fl & SLEEP_ALLOW_SPURIOUS) {
1370 woke = vm_check_ints_blocking(th->ec);
1372 if (woke && !(fl & SLEEP_SPURIOUS_CHECK)) {
1376 th->status = prev_status;
1382 RUBY_DEBUG_LOG(
"forever");
1383 sleep_forever(GET_THREAD(), SLEEP_SPURIOUS_CHECK);
1389 RUBY_DEBUG_LOG(
"deadly");
1390 sleep_forever(GET_THREAD(), SLEEP_DEADLOCKABLE|SLEEP_SPURIOUS_CHECK);
1394 rb_thread_sleep_deadly_allow_spurious_wakeup(
VALUE blocker,
VALUE timeout, rb_hrtime_t end)
1397 if (scheduler !=
Qnil) {
1401 RUBY_DEBUG_LOG(
"...");
1403 sleep_hrtime_until(GET_THREAD(), end, SLEEP_SPURIOUS_CHECK);
1406 sleep_forever(GET_THREAD(), SLEEP_DEADLOCKABLE);
1416 sleep_hrtime(th, rb_timeval2hrtime(&time), SLEEP_SPURIOUS_CHECK);
1422 RUBY_VM_CHECK_INTS_BLOCKING(ec);
1435 rb_ec_check_ints(GET_EC());
1443 rb_thread_check_trap_pending(
void)
1445 return rb_signal_buff_size() != 0;
1452 return (
int)RUBY_VM_INTERRUPTED(rb_thread_ptr(thval)->ec);
1462 rb_thread_schedule_limits(uint32_t limits_us)
1466 RUBY_DEBUG_LOG(
"us:%u", (
unsigned int)limits_us);
1468 if (th->running_time_us >= limits_us) {
1469 RUBY_DEBUG_LOG(
"switch %s",
"start");
1471 RB_VM_SAVE_MACHINE_CONTEXT(th);
1472 thread_sched_yield(TH_SCHED(th), th);
1473 rb_ractor_thread_switch(th->ractor, th);
1475 RUBY_DEBUG_LOG(
"switch %s",
"done");
1483 rb_thread_schedule_limits(0);
1484 RUBY_VM_CHECK_INTS(GET_EC());
1493 #ifdef RUBY_ASSERT_CRITICAL_SECTION
1494 VM_ASSERT(ruby_assert_critical_section_entered == 0);
1496 VM_ASSERT(th == GET_THREAD());
1498 region->prev_status = th->status;
1499 if (unblock_function_set(th, ubf, arg, fail_if_interrupted)) {
1500 th->blocking_region_buffer = region;
1501 th->status = THREAD_STOPPED;
1502 rb_ractor_blocking_threads_inc(th->ractor, __FILE__, __LINE__);
1504 RUBY_DEBUG_LOG(
"thread_id:%p", (
void *)th->nt->thread_id);
1516 unblock_function_clear(th);
1518 unregister_ubf_list(th);
1520 thread_sched_to_running(TH_SCHED(th), th);
1521 rb_ractor_thread_switch(th->ractor, th);
1523 th->blocking_region_buffer = 0;
1524 rb_ractor_blocking_threads_dec(th->ractor, __FILE__, __LINE__);
1525 if (th->status == THREAD_STOPPED) {
1526 th->status = region->prev_status;
1529 RUBY_DEBUG_LOG(
"end");
1533 VM_ASSERT(th == GET_THREAD());
1538 rb_nogvl(
void *(*func)(
void *),
void *data1,
1544 if (scheduler !=
Qnil) {
1549 if (!UNDEF_P(result)) {
1551 return state.result;
1559 rb_vm_t *vm = rb_ec_vm_ptr(ec);
1560 bool is_main_thread = vm->ractor.main_thread == th;
1561 int saved_errno = 0;
1567 else if (ubf && rb_ractor_living_thread_num(th->ractor) == 1 && is_main_thread) {
1569 vm->ubf_async_safe = 1;
1573 rb_vm_t *
volatile saved_vm = vm;
1574 BLOCKING_REGION(th, {
1580 if (is_main_thread) vm->ubf_async_safe = 0;
1583 RUBY_VM_CHECK_INTS_BLOCKING(ec);
1687 return rb_nogvl(func, data1, ubf, data2, 0);
1691 waitfd_to_waiting_flag(
int wfd_event)
1693 return wfd_event << 1;
1705 ccan_list_add(&th->vm->waiting_fds, &wfd->wfd_node);
1711 thread_io_wake_pending_closer(
struct waiting_fd *wfd)
1713 bool has_waiter = wfd->busy &&
RB_TEST(wfd->busy->wakeup_mutex);
1722 ccan_list_del(&wfd->wfd_node);
1726 rb_thread_t *th = rb_thread_ptr(wfd->busy->closing_thread);
1727 if (th->scheduler !=
Qnil) {
1739 #if defined(USE_MN_THREADS) && USE_MN_THREADS
1740 return !th_has_dedicated_nt(th) && (events || timeout) && th->blocking;
1748 thread_io_wait_events(
rb_thread_t *th,
int fd,
int events,
const struct timeval *timeout)
1750 #if defined(USE_MN_THREADS) && USE_MN_THREADS
1751 if (thread_io_mn_schedulable(th, events, timeout)) {
1752 rb_hrtime_t rel, *prel;
1755 rel = rb_timeval2hrtime(timeout);
1762 VM_ASSERT(prel || (events & (RB_WAITFD_IN | RB_WAITFD_OUT)));
1764 if (thread_sched_wait_events(TH_SCHED(th), th, fd, waitfd_to_waiting_flag(events), prel)) {
1778 blocking_call_retryable_p(
int r,
int eno)
1780 if (r != -1)
return false;
1784 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
1794 rb_thread_mn_schedulable(
VALUE thval)
1797 return th->mn_schedulable;
1801 rb_thread_io_blocking_call(rb_blocking_function_t *func,
void *data1,
int fd,
int events)
1806 RUBY_DEBUG_LOG(
"th:%u fd:%d ev:%d", rb_th_serial(th), fd, events);
1810 volatile int saved_errno = 0;
1811 enum ruby_tag_type state;
1812 bool prev_mn_schedulable = th->mn_schedulable;
1813 th->mn_schedulable = thread_io_mn_schedulable(th, events, NULL);
1824 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
1825 volatile enum ruby_tag_type saved_state = state;
1829 saved_errno = errno;
1832 th = rb_ec_thread_ptr(ec);
1834 blocking_call_retryable_p((
int)val, saved_errno) &&
1835 thread_io_wait_events(th, fd, events, NULL)) {
1836 RUBY_VM_CHECK_INTS_BLOCKING(ec);
1839 state = saved_state;
1843 th = rb_ec_thread_ptr(ec);
1844 th->mn_schedulable = prev_mn_schedulable;
1853 EC_JUMP_TAG(ec, state);
1856 RUBY_VM_CHECK_INTS_BLOCKING(ec);
1859 if (saved_errno == ETIMEDOUT) {
1863 errno = saved_errno;
1869 rb_thread_io_blocking_region(rb_blocking_function_t *func,
void *data1,
int fd)
1871 return rb_thread_io_blocking_call(func, data1, fd, 0);
1916 fprintf(stderr,
"[BUG] rb_thread_call_with_gvl() is called by non-ruby thread\n");
1921 prev_unblock = th->unblock;
1924 rb_bug(
"rb_thread_call_with_gvl: called by a thread which has GVL.");
1927 blocking_region_end(th, brb);
1931 int released = blocking_region_begin(th, brb, prev_unblock.func, prev_unblock.arg, FALSE);
1933 RB_VM_SAVE_MACHINE_CONTEXT(th);
1934 thread_sched_to_waiting(TH_SCHED(th), th);
1948 ruby_thread_has_gvl_p(
void)
1952 if (th && th->blocking_region_buffer == 0) {
1969 thread_s_pass(
VALUE klass)
1994 rb_threadptr_pending_interrupt_clear(
rb_thread_t *th)
2003 th->pending_interrupt_queue_checked = 0;
2007 threadptr_check_pending_interrupt_queue(
rb_thread_t *th)
2009 if (!th->pending_interrupt_queue) {
2014 enum handle_interrupt_timing {
2016 INTERRUPT_IMMEDIATE,
2017 INTERRUPT_ON_BLOCKING,
2021 static enum handle_interrupt_timing
2024 if (sym == sym_immediate) {
2025 return INTERRUPT_IMMEDIATE;
2027 else if (sym == sym_on_blocking) {
2028 return INTERRUPT_ON_BLOCKING;
2030 else if (sym == sym_never) {
2031 return INTERRUPT_NEVER;
2038 static enum handle_interrupt_timing
2042 long mask_stack_len =
RARRAY_LEN(th->pending_interrupt_mask_stack);
2047 for (i=0; i<mask_stack_len; i++) {
2048 mask = mask_stack[mask_stack_len-(i+1)];
2053 return rb_threadptr_pending_interrupt_from_symbol(th, mask);
2065 klass =
RBASIC(mod)->klass;
2067 else if (mod != RCLASS_ORIGIN(mod)) {
2072 return rb_threadptr_pending_interrupt_from_symbol(th, sym);
2077 return INTERRUPT_NONE;
2081 rb_threadptr_pending_interrupt_empty_p(
const rb_thread_t *th)
2083 return RARRAY_LEN(th->pending_interrupt_queue) == 0;
2090 for (i=0; i<
RARRAY_LEN(th->pending_interrupt_queue); i++) {
2100 rb_threadptr_pending_interrupt_deque(
rb_thread_t *th,
enum handle_interrupt_timing timing)
2105 for (i=0; i<
RARRAY_LEN(th->pending_interrupt_queue); i++) {
2108 enum handle_interrupt_timing mask_timing = rb_threadptr_pending_interrupt_check_mask(th,
CLASS_OF(err));
2110 switch (mask_timing) {
2111 case INTERRUPT_ON_BLOCKING:
2112 if (timing != INTERRUPT_ON_BLOCKING) {
2116 case INTERRUPT_NONE:
2117 case INTERRUPT_IMMEDIATE:
2120 case INTERRUPT_NEVER:
2125 th->pending_interrupt_queue_checked = 1;
2129 if (rb_threadptr_pending_interrupt_empty_p(th)) {
2130 th->pending_interrupt_queue_checked = 1;
2137 threadptr_pending_interrupt_active_p(
rb_thread_t *th)
2144 if (th->pending_interrupt_queue_checked) {
2148 if (rb_threadptr_pending_interrupt_empty_p(th)) {
2160 if (val != sym_immediate && val != sym_on_blocking && val != sym_never) {
2169 if (
RTEST(*maskp)) {
2171 VALUE prev = *maskp;
2172 *maskp = rb_ident_hash_new();
2271 rb_thread_s_handle_interrupt(
VALUE self,
VALUE mask_arg)
2277 enum ruby_tag_type state;
2283 mask_arg = rb_to_hash_type(mask_arg);
2285 if (
OBJ_FROZEN(mask_arg) && rb_hash_compare_by_id_p(mask_arg)) {
2291 if (UNDEF_P(mask)) {
2302 rb_ary_push(th->pending_interrupt_mask_stack, mask);
2303 if (!rb_threadptr_pending_interrupt_empty_p(th)) {
2304 th->pending_interrupt_queue_checked = 0;
2305 RUBY_VM_SET_INTERRUPT(th->ec);
2308 EC_PUSH_TAG(th->ec);
2309 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
2314 rb_ary_pop(th->pending_interrupt_mask_stack);
2315 if (!rb_threadptr_pending_interrupt_empty_p(th)) {
2316 th->pending_interrupt_queue_checked = 0;
2317 RUBY_VM_SET_INTERRUPT(th->ec);
2320 RUBY_VM_CHECK_INTS(th->ec);
2323 EC_JUMP_TAG(th->ec, state);
2340 rb_thread_pending_interrupt_p(
int argc,
VALUE *argv,
VALUE target_thread)
2342 rb_thread_t *target_th = rb_thread_ptr(target_thread);
2344 if (!target_th->pending_interrupt_queue) {
2347 if (rb_threadptr_pending_interrupt_empty_p(target_th)) {
2351 VALUE err = argv[0];
2355 return RBOOL(rb_threadptr_pending_interrupt_include_p(target_th, err));
2420 rb_thread_s_pending_interrupt_p(
int argc,
VALUE *argv,
VALUE self)
2422 return rb_thread_pending_interrupt_p(argc, argv, GET_THREAD()->
self);
2425 NORETURN(
static void rb_threadptr_to_kill(
rb_thread_t *th));
2430 rb_threadptr_pending_interrupt_clear(th);
2431 th->status = THREAD_RUNNABLE;
2433 th->ec->errinfo =
INT2FIX(TAG_FATAL);
2434 EC_JUMP_TAG(th->ec, TAG_FATAL);
2445 interrupt = ec->interrupt_flag;
2446 old = ATOMIC_CAS(ec->interrupt_flag, interrupt, interrupt & ec->interrupt_mask);
2447 }
while (old != interrupt);
2448 return interrupt & (
rb_atomic_t)~ec->interrupt_mask;
2451 static void threadptr_interrupt_exec_exec(
rb_thread_t *th);
2454 rb_threadptr_execute_interrupts(
rb_thread_t *th,
int blocking_timing)
2457 int postponed_job_interrupt = 0;
2460 if (th->ec->raised_flag)
return ret;
2462 while ((interrupt = threadptr_get_interrupts(th)) != 0) {
2464 int timer_interrupt;
2465 int pending_interrupt;
2467 int terminate_interrupt;
2469 timer_interrupt = interrupt & TIMER_INTERRUPT_MASK;
2470 pending_interrupt = interrupt & PENDING_INTERRUPT_MASK;
2471 postponed_job_interrupt = interrupt & POSTPONED_JOB_INTERRUPT_MASK;
2472 trap_interrupt = interrupt & TRAP_INTERRUPT_MASK;
2473 terminate_interrupt = interrupt & TERMINATE_INTERRUPT_MASK;
2475 if (interrupt & VM_BARRIER_INTERRUPT_MASK) {
2480 if (postponed_job_interrupt) {
2481 rb_postponed_job_flush(th->vm);
2484 if (trap_interrupt) {
2486 if (th == th->vm->ractor.main_thread) {
2487 enum rb_thread_status prev_status = th->status;
2489 th->status = THREAD_RUNNABLE;
2491 while ((sig = rb_get_next_signal()) != 0) {
2492 ret |= rb_signal_exec(th, sig);
2495 th->status = prev_status;
2498 if (!ccan_list_empty(&th->interrupt_exec_tasks)) {
2499 enum rb_thread_status prev_status = th->status;
2501 th->status = THREAD_RUNNABLE;
2503 threadptr_interrupt_exec_exec(th);
2505 th->status = prev_status;
2510 if (pending_interrupt && threadptr_pending_interrupt_active_p(th)) {
2511 VALUE err = rb_threadptr_pending_interrupt_deque(th, blocking_timing ? INTERRUPT_ON_BLOCKING : INTERRUPT_NONE);
2512 RUBY_DEBUG_LOG(
"err:%"PRIdVALUE, err);
2518 else if (err == RUBY_FATAL_THREAD_KILLED ||
2519 err == RUBY_FATAL_THREAD_TERMINATED ||
2521 terminate_interrupt = 1;
2524 if (err == th->vm->special_exceptions[ruby_error_stream_closed]) {
2526 err = ruby_vm_special_exception_copy(err);
2529 if (th->status == THREAD_STOPPED ||
2530 th->status == THREAD_STOPPED_FOREVER)
2531 th->status = THREAD_RUNNABLE;
2536 if (terminate_interrupt) {
2537 rb_threadptr_to_kill(th);
2540 if (timer_interrupt) {
2541 uint32_t limits_us = TIME_QUANTUM_USEC;
2543 if (th->priority > 0)
2544 limits_us <<= th->priority;
2546 limits_us >>= -th->priority;
2548 if (th->status == THREAD_RUNNABLE)
2549 th->running_time_us += 10 * 1000;
2551 VM_ASSERT(th->ec->cfp);
2555 rb_thread_schedule_limits(limits_us);
2562 rb_thread_execute_interrupts(
VALUE thval)
2564 rb_threadptr_execute_interrupts(rb_thread_ptr(thval), 1);
2570 rb_threadptr_interrupt(th);
2578 if (rb_threadptr_dead(target_th)) {
2591 if (rb_threadptr_dead(target_th)) {
2595 rb_ec_setup_exception(GET_EC(), exc,
Qundef);
2596 rb_threadptr_pending_interrupt_enque(target_th, exc);
2597 rb_threadptr_interrupt(target_th);
2602 rb_threadptr_signal_raise(
rb_thread_t *th,
int sig)
2608 rb_threadptr_raise(th->vm->ractor.main_thread, 2, argv);
2620 rb_threadptr_raise(th->vm->ractor.main_thread, 2, argv);
2626 if (ec->raised_flag & RAISED_EXCEPTION) {
2629 ec->raised_flag |= RAISED_EXCEPTION;
2636 if (!(ec->raised_flag & RAISED_EXCEPTION)) {
2639 ec->raised_flag &= ~RAISED_EXCEPTION;
2646 rb_vm_t *vm = GET_THREAD()->vm;
2648 ccan_list_head_init(&busy->pending_fd_users);
2654 ccan_list_for_each_safe(&vm->waiting_fds, wfd, next, wfd_node) {
2655 if (wfd->fd == fd) {
2659 ccan_list_del(&wfd->wfd_node);
2660 ccan_list_add(&busy->pending_fd_users, &wfd->wfd_node);
2663 err = th->vm->special_exceptions[ruby_error_stream_closed];
2664 rb_threadptr_pending_interrupt_enque(th, err);
2665 rb_threadptr_interrupt(th);
2670 has_any = !ccan_list_empty(&busy->pending_fd_users);
2673 wakeup_mutex =
Qnil;
2676 RBASIC_CLEAR_CLASS(wakeup_mutex);
2678 busy->wakeup_mutex = wakeup_mutex;
2692 if (!
RB_TEST(busy->wakeup_mutex)) {
2699 while (!ccan_list_empty(&busy->pending_fd_users)) {
2710 if (rb_notify_fd_close(fd, &busy)) {
2711 rb_notify_fd_close_wait(&busy);
2737 thread_raise_m(
int argc,
VALUE *argv,
VALUE self)
2742 threadptr_check_pending_interrupt_queue(target_th);
2743 rb_threadptr_raise(target_th, argc, argv);
2746 if (current_th == target_th) {
2747 RUBY_VM_CHECK_INTS(target_th->ec);
2769 if (target_th->to_kill || target_th->status == THREAD_KILLED) {
2772 if (target_th == target_th->vm->ractor.main_thread) {
2776 RUBY_DEBUG_LOG(
"target_th:%u", rb_th_serial(target_th));
2778 if (target_th == GET_THREAD()) {
2780 rb_threadptr_to_kill(target_th);
2783 threadptr_check_pending_interrupt_queue(target_th);
2784 rb_threadptr_pending_interrupt_enque(target_th, RUBY_FATAL_THREAD_KILLED);
2785 rb_threadptr_interrupt(target_th);
2792 rb_thread_to_be_killed(
VALUE thread)
2796 if (target_th->to_kill || target_th->status == THREAD_KILLED) {
2872 if (target_th->status == THREAD_KILLED)
return Qnil;
2874 rb_threadptr_ready(target_th);
2876 if (target_th->status == THREAD_STOPPED ||
2877 target_th->status == THREAD_STOPPED_FOREVER) {
2878 target_th->status = THREAD_RUNNABLE;
2920 "stopping only thread\n\tnote: use sleep to stop forever");
2950 rb_thread_list(
void)
2953 return rb_ractor_thread_list();
2979 return rb_thread_list();
2985 return GET_THREAD()->self;
2998 thread_s_current(
VALUE klass)
3006 return GET_RACTOR()->threads.main->self;
3017 rb_thread_s_main(
VALUE klass)
3044 rb_thread_s_abort_exc(
VALUE _)
3046 return RBOOL(GET_THREAD()->vm->thread_abort_on_exception);
3081 rb_thread_s_abort_exc_set(
VALUE self,
VALUE val)
3083 GET_THREAD()->vm->thread_abort_on_exception =
RTEST(val);
3104 rb_thread_abort_exc(
VALUE thread)
3106 return RBOOL(rb_thread_ptr(thread)->abort_on_exception);
3124 rb_thread_abort_exc_set(
VALUE thread,
VALUE val)
3126 rb_thread_ptr(thread)->abort_on_exception =
RTEST(val);
3174 rb_thread_s_report_exc(
VALUE _)
3176 return RBOOL(GET_THREAD()->vm->thread_report_on_exception);
3211 rb_thread_s_report_exc_set(
VALUE self,
VALUE val)
3213 GET_THREAD()->vm->thread_report_on_exception =
RTEST(val);
3230 rb_thread_s_ignore_deadlock(
VALUE _)
3232 return RBOOL(GET_THREAD()->vm->thread_ignore_deadlock);
3257 rb_thread_s_ignore_deadlock_set(
VALUE self,
VALUE val)
3259 GET_THREAD()->vm->thread_ignore_deadlock =
RTEST(val);
3281 rb_thread_report_exc(
VALUE thread)
3283 return RBOOL(rb_thread_ptr(thread)->report_on_exception);
3301 rb_thread_report_exc_set(
VALUE thread,
VALUE val)
3303 rb_thread_ptr(thread)->report_on_exception =
RTEST(val);
3318 rb_thread_group(
VALUE thread)
3320 return rb_thread_ptr(thread)->thgroup;
3326 switch (th->status) {
3327 case THREAD_RUNNABLE:
3328 return th->to_kill ?
"aborting" :
"run";
3329 case THREAD_STOPPED_FOREVER:
3330 if (detail)
return "sleep_forever";
3331 case THREAD_STOPPED:
3343 return th->status == THREAD_KILLED;
3379 rb_thread_status(
VALUE thread)
3383 if (rb_threadptr_dead(target_th)) {
3384 if (!
NIL_P(target_th->ec->errinfo) &&
3385 !
FIXNUM_P(target_th->ec->errinfo)) {
3393 return rb_str_new2(thread_status_name(target_th, FALSE));
3413 rb_thread_alive_p(
VALUE thread)
3415 return RBOOL(!thread_finished(rb_thread_ptr(thread)));
3433 rb_thread_stop_p(
VALUE thread)
3437 if (rb_threadptr_dead(th)) {
3440 return RBOOL(th->status == THREAD_STOPPED || th->status == THREAD_STOPPED_FOREVER);
3451 rb_thread_getname(
VALUE thread)
3453 return rb_thread_ptr(thread)->name;
3479 target_th->name = name;
3480 if (threadptr_initialized(target_th) && target_th->has_dedicated_nt) {
3481 native_set_another_thread_name(target_th->nt->thread_id, name);
3486 #if USE_NATIVE_THREAD_NATIVE_THREAD_ID
3510 rb_thread_native_thread_id(
VALUE thread)
3513 if (rb_threadptr_dead(target_th))
return Qnil;
3514 return native_thread_native_thread_id(target_th);
3517 # define rb_thread_native_thread_id rb_f_notimplement
3528 rb_thread_to_s(
VALUE thread)
3535 status = thread_status_name(target_th, TRUE);
3536 str =
rb_sprintf(
"#<%"PRIsVALUE
":%p", cname, (
void *)thread);
3537 if (!
NIL_P(target_th->name)) {
3540 if ((loc = threadptr_invoke_proc_location(target_th)) !=
Qnil) {
3550 #define recursive_key id__recursive_key__
3555 if (
id == recursive_key) {
3556 return th->ec->local_storage_recursive_hash;
3560 struct rb_id_table *local_storage = th->ec->local_storage;
3562 if (local_storage != NULL && rb_id_table_lookup(local_storage,
id, &val)) {
3574 return threadptr_local_aref(rb_thread_ptr(thread),
id);
3641 if (!
id)
return Qnil;
3659 rb_thread_fetch(
int argc,
VALUE *argv,
VALUE self)
3670 if (block_given && argc == 2) {
3671 rb_warn(
"block supersedes default value argument");
3676 if (
id == recursive_key) {
3677 return target_th->ec->local_storage_recursive_hash;
3679 else if (
id && target_th->ec->local_storage &&
3680 rb_id_table_lookup(target_th->ec->local_storage,
id, &val)) {
3683 else if (block_given) {
3686 else if (argc == 1) {
3687 rb_key_err_raise(
rb_sprintf(
"key not found: %+"PRIsVALUE, key),
self, key);
3697 if (
id == recursive_key) {
3698 th->ec->local_storage_recursive_hash = val;
3702 struct rb_id_table *local_storage = th->ec->local_storage;
3705 if (!local_storage)
return Qnil;
3706 rb_id_table_delete(local_storage,
id);
3710 if (local_storage == NULL) {
3711 th->ec->local_storage = local_storage = rb_id_table_create(0);
3713 rb_id_table_insert(local_storage,
id, val);
3726 return threadptr_local_aset(rb_thread_ptr(thread),
id, val);
3777 rb_thread_variable_get(
VALUE thread,
VALUE key)
3782 if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
3785 locals = rb_thread_local_storage(thread);
3807 locals = rb_thread_local_storage(thread);
3829 struct rb_id_table *local_storage = rb_thread_ptr(
self)->ec->local_storage;
3831 if (!
id || local_storage == NULL) {
3834 return RBOOL(rb_id_table_lookup(local_storage,
id, &val));
3837 static enum rb_id_table_iterator_result
3838 thread_keys_i(
ID key,
VALUE value,
void *ary)
3841 return ID_TABLE_CONTINUE;
3848 return rb_ractor_living_thread_num(GET_RACTOR()) == 1;
3866 rb_thread_keys(
VALUE self)
3868 struct rb_id_table *local_storage = rb_thread_ptr(
self)->ec->local_storage;
3871 if (local_storage) {
3872 rb_id_table_foreach(local_storage, thread_keys_i, (
void *)ary);
3902 rb_thread_variables(
VALUE thread)
3908 if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
3911 locals = rb_thread_local_storage(thread);
3934 rb_thread_variable_p(
VALUE thread,
VALUE key)
3939 if (LIKELY(!THREAD_LOCAL_STORAGE_INITIALISED_P(thread))) {
3942 locals = rb_thread_local_storage(thread);
3963 rb_thread_priority(
VALUE thread)
3965 return INT2NUM(rb_thread_ptr(thread)->priority);
3996 rb_thread_priority_set(
VALUE thread,
VALUE prio)
4001 #if USE_NATIVE_THREAD_PRIORITY
4002 target_th->priority =
NUM2INT(prio);
4003 native_thread_apply_priority(th);
4006 if (priority > RUBY_THREAD_PRIORITY_MAX) {
4007 priority = RUBY_THREAD_PRIORITY_MAX;
4009 else if (priority < RUBY_THREAD_PRIORITY_MIN) {
4010 priority = RUBY_THREAD_PRIORITY_MIN;
4012 target_th->priority = (int8_t)priority;
4014 return INT2NUM(target_th->priority);
4019 #if defined(NFDBITS) && defined(HAVE_RB_FD_INIT)
4055 FD_ZERO(fds->
fdset);
4061 size_t size = howmany(
rb_fd_max(src), NFDBITS) *
sizeof(fd_mask);
4063 if (size <
sizeof(fd_set))
4064 size =
sizeof(fd_set);
4088 size_t m = howmany(n + 1, NFDBITS) *
sizeof(fd_mask);
4089 size_t o = howmany(fds->
maxfd, NFDBITS) *
sizeof(fd_mask);
4091 if (m <
sizeof(fd_set)) m =
sizeof(fd_set);
4092 if (o <
sizeof(fd_set)) o =
sizeof(fd_set);
4096 memset((
char *)fds->
fdset + o, 0, m - o);
4105 FD_SET(n, fds->
fdset);
4111 if (n >= fds->
maxfd)
return;
4112 FD_CLR(n, fds->
fdset);
4118 if (n >= fds->
maxfd)
return 0;
4119 return FD_ISSET(n, fds->
fdset) != 0;
4125 size_t size = howmany(max, NFDBITS) *
sizeof(fd_mask);
4127 if (size <
sizeof(fd_set)) size =
sizeof(fd_set);
4130 memcpy(dst->
fdset, src, size);
4136 size_t size = howmany(
rb_fd_max(src), NFDBITS) *
sizeof(fd_mask);
4138 if (size <
sizeof(fd_set))
4139 size =
sizeof(fd_set);
4148 fd_set *r = NULL, *w = NULL, *e = NULL;
4161 return select(n, r, w, e, timeout);
4164 #define rb_fd_no_init(fds) ((void)((fds)->fdset = 0), (void)((fds)->maxfd = 0))
4171 #define FD_ZERO(f) rb_fd_zero(f)
4172 #define FD_SET(i, f) rb_fd_set((i), (f))
4173 #define FD_CLR(i, f) rb_fd_clr((i), (f))
4174 #define FD_ISSET(i, f) rb_fd_isset((i), (f))
4176 #elif defined(_WIN32)
4181 set->
capa = FD_SETSIZE;
4183 FD_ZERO(set->
fdset);
4205 SOCKET s = rb_w32_get_osfhandle(fd);
4207 for (i = 0; i < set->
fdset->fd_count; i++) {
4208 if (set->
fdset->fd_array[i] == s) {
4212 if (set->
fdset->fd_count >= (
unsigned)set->
capa) {
4213 set->
capa = (set->
fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
4215 rb_xrealloc_mul_add(
4216 set->
fdset, set->
capa,
sizeof(SOCKET),
sizeof(
unsigned int));
4218 set->
fdset->fd_array[set->
fdset->fd_count++] = s;
4226 #define FD_ZERO(f) rb_fd_zero(f)
4227 #define FD_SET(i, f) rb_fd_set((i), (f))
4228 #define FD_CLR(i, f) rb_fd_clr((i), (f))
4229 #define FD_ISSET(i, f) rb_fd_isset((i), (f))
4231 #define rb_fd_no_init(fds) (void)((fds)->fdset = 0)
4235 #ifndef rb_fd_no_init
4236 #define rb_fd_no_init(fds) (void)(fds)
4240 wait_retryable(
volatile int *result,
int errnum, rb_hrtime_t *rel, rb_hrtime_t end)
4250 if (rel && hrtime_update_expire(rel, end)) {
4260 return !hrtime_update_expire(rel, end);
4280 select_set_free(
VALUE p)
4295 volatile int result = 0;
4297 rb_hrtime_t *to, rel, end = 0;
4299 timeout_prepare(&to, &rel, &end, set->timeout);
4300 volatile rb_hrtime_t endtime = end;
4301 #define restore_fdset(dst, src) \
4302 ((dst) ? rb_fd_dup(dst, src) : (void)0)
4303 #define do_select_update() \
4304 (restore_fdset(set->rset, &set->orig_rset), \
4305 restore_fdset(set->wset, &set->orig_wset), \
4306 restore_fdset(set->eset, &set->orig_eset), \
4312 BLOCKING_REGION(set->th, {
4315 if (!RUBY_VM_INTERRUPTED(set->th->ec)) {
4316 result = native_fd_select(set->max,
4317 set->rset, set->wset, set->eset,
4318 rb_hrtime2timeval(&tv, to), set->th);
4319 if (result < 0) lerrno = errno;
4321 }, ubf_select, set->th, TRUE);
4323 RUBY_VM_CHECK_INTS_BLOCKING(set->th->ec);
4324 }
while (wait_retryable(&result, lerrno, to, endtime) && do_select_update());
4330 return (
VALUE)result;
4339 set.th = GET_THREAD();
4340 RUBY_VM_CHECK_INTS_BLOCKING(set.th->ec);
4345 set.timeout = timeout;
4347 if (!set.rset && !set.wset && !set.eset) {
4356 #define fd_init_copy(f) do { \
4358 rb_fd_resize(set.max - 1, set.f); \
4359 if (&set.orig_##f != set.f) { \
4360 rb_fd_init_copy(&set.orig_##f, set.f); \
4364 rb_fd_no_init(&set.orig_##f); \
4378 #define POLLIN_SET (POLLRDNORM | POLLRDBAND | POLLIN | POLLHUP | POLLERR)
4379 #define POLLOUT_SET (POLLWRBAND | POLLWRNORM | POLLOUT | POLLERR)
4380 #define POLLEX_SET (POLLPRI)
4383 # define POLLERR_SET (0)
4387 wait_for_single_fd_blocking_region(
rb_thread_t *th,
struct pollfd *fds, nfds_t nfds,
4388 rb_hrtime_t *
const to,
volatile int *lerrno)
4391 volatile int result = 0;
4394 BLOCKING_REGION(th, {
4395 if (!RUBY_VM_INTERRUPTED(th->ec)) {
4396 result = ppoll(fds, nfds, rb_hrtime2timespec(&ts, to), 0);
4397 if (result < 0) *lerrno = errno;
4399 }, ubf_select, th, TRUE);
4407 rb_thread_wait_for_single_fd(
int fd,
int events,
struct timeval *timeout)
4409 struct pollfd fds[1] = {{
4411 .events = (short)events,
4414 volatile int result = 0;
4417 enum ruby_tag_type state;
4418 volatile int lerrno;
4423 thread_io_setup_wfd(th, fd, &wfd);
4425 if (timeout == NULL && thread_io_wait_events(th, fd, events, NULL)) {
4428 fds[0].revents = events;
4432 EC_PUSH_TAG(wfd.th->ec);
4433 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
4434 rb_hrtime_t *to, rel, end = 0;
4435 RUBY_VM_CHECK_INTS_BLOCKING(wfd.th->ec);
4436 timeout_prepare(&to, &rel, &end, timeout);
4438 nfds = numberof(fds);
4439 result = wait_for_single_fd_blocking_region(wfd.th, fds, nfds, to, &lerrno);
4441 RUBY_VM_CHECK_INTS_BLOCKING(wfd.th->ec);
4442 }
while (wait_retryable(&result, lerrno, to, end));
4447 thread_io_wake_pending_closer(&wfd);
4450 EC_JUMP_TAG(wfd.th->ec, state);
4458 if (fds[0].revents & POLLNVAL) {
4468 if (fds[0].revents & POLLIN_SET)
4469 result |= RB_WAITFD_IN;
4470 if (fds[0].revents & POLLOUT_SET)
4471 result |= RB_WAITFD_OUT;
4472 if (fds[0].revents & POLLEX_SET)
4473 result |= RB_WAITFD_PRI;
4476 if (fds[0].revents & POLLERR_SET)
4501 args->read, args->write, args->except, args->tv);
4503 args->as.error =
errno;
4506 if (args->read &&
rb_fd_isset(args->as.fd, args->read))
4508 if (args->write &&
rb_fd_isset(args->as.fd, args->write))
4510 if (args->except &&
rb_fd_isset(args->as.fd, args->except))
4521 thread_io_wake_pending_closer(&args->wfd);
4542 rb_thread_wait_for_single_fd(
int fd,
int events,
struct timeval *timeout)
4552 args.read = (events & RB_WAITFD_IN) ? init_set_fd(fd, &rfds) : NULL;
4553 args.write = (events & RB_WAITFD_OUT) ? init_set_fd(fd, &wfds) : NULL;
4554 args.except = (events & RB_WAITFD_PRI) ? init_set_fd(fd, &efds) : NULL;
4556 thread_io_setup_wfd(th, fd, &args.wfd);
4560 errno = args.as.error;
4570 #ifdef USE_CONSERVATIVE_STACK_END
4572 rb_gc_set_stack_end(
VALUE **stack_end_p)
4575 COMPILER_WARNING_PUSH
4576 #if __has_warning("-Wdangling-pointer")
4577 COMPILER_WARNING_IGNORED(-Wdangling-pointer);
4579 *stack_end_p = &stack_end;
4580 COMPILER_WARNING_POP
4592 if (rb_signal_buff_size() > 0) {
4594 threadptr_trap_interrupt(mth);
4599 async_bug_fd(
const char *mesg,
int errno_arg,
int fd)
4602 size_t n = strlcpy(buff, mesg,
sizeof(buff));
4603 if (n <
sizeof(buff)-3) {
4606 rb_async_bug_errno(buff, errno_arg);
4611 consume_communication_pipe(
int fd)
4617 static char buff[1024];
4623 result = read(fd, buff,
sizeof(buff));
4625 RUBY_DEBUG_LOG(
"resultf:%d buff:%lu", (
int)result, (
unsigned long)buff[0]);
4627 RUBY_DEBUG_LOG(
"result:%d", (
int)result);
4631 if (USE_EVENTFD || result < (ssize_t)
sizeof(buff)) {
4635 else if (result == 0) {
4638 else if (result < 0) {
4644 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
4649 async_bug_fd(
"consume_communication_pipe: read", e, fd);
4656 rb_thread_stop_timer_thread(
void)
4658 if (TIMER_THREAD_CREATED_P() && native_stop_timer_thread()) {
4659 native_reset_timer_thread();
4664 rb_thread_reset_timer_thread(
void)
4666 native_reset_timer_thread();
4670 rb_thread_start_timer_thread(
void)
4673 rb_thread_create_timer_thread();
4677 clear_coverage_i(st_data_t key, st_data_t val, st_data_t dummy)
4685 if (GET_VM()->coverage_mode & COVERAGE_TARGET_ONESHOT_LINES) {
4707 rb_clear_coverages(
void)
4709 VALUE coverages = rb_get_coverages();
4710 if (
RTEST(coverages)) {
4715 #if defined(HAVE_WORKING_FORK)
4723 vm->ractor.main_ractor = r;
4724 vm->ractor.main_thread = th;
4725 r->threads.main = th;
4726 r->status_ = ractor_created;
4728 thread_sched_atfork(TH_SCHED(th));
4732 ccan_list_for_each(&vm->ractor.set, r, vmlr_node) {
4733 ccan_list_for_each(&r->threads.set, i, lt_node) {
4737 rb_vm_living_threads_init(vm);
4739 rb_ractor_atfork(vm, th);
4740 rb_vm_postponed_job_atfork();
4747 ccan_list_head_init(&th->interrupt_exec_tasks);
4750 rb_ractor_sleeper_threads_clear(th->ractor);
4751 rb_clear_coverages();
4754 rb_thread_reset_timer_thread();
4755 rb_thread_start_timer_thread();
4757 VM_ASSERT(vm->ractor.blocking_cnt == 0);
4758 VM_ASSERT(vm->ractor.cnt == 1);
4764 if (th != current_th) {
4765 rb_mutex_abandon_keeping_mutexes(th);
4766 rb_mutex_abandon_locking_mutex(th);
4767 thread_cleanup_func(th, TRUE);
4776 rb_threadptr_pending_interrupt_clear(th);
4777 rb_thread_atfork_internal(th, terminate_atfork_i);
4778 th->join_list = NULL;
4779 rb_fiber_atfork(th);
4788 if (th != current_th) {
4789 thread_cleanup_func_before_exec(th);
4797 rb_thread_atfork_internal(th, terminate_atfork_before_exec_i);
4822 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE
4845 thgroup_s_alloc(
VALUE klass)
4866 thgroup_list(
VALUE group)
4872 ccan_list_for_each(&r->threads.set, th, lt_node) {
4873 if (th->thgroup == group) {
4898 thgroup_enclose(
VALUE group)
4917 thgroup_enclosed_p(
VALUE group)
4922 return RBOOL(data->enclosed);
4962 if (data->enclosed) {
4970 if (data->enclosed) {
4972 "can't move from the enclosed thread group");
4975 target_th->thgroup = group;
4983 thread_shield_mark(
void *
ptr)
4990 {thread_shield_mark, 0, 0,},
4991 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
4995 thread_shield_alloc(
VALUE klass)
5000 #define GetThreadShieldPtr(obj) ((VALUE)rb_check_typeddata((obj), &thread_shield_data_type))
5001 #define THREAD_SHIELD_WAITING_MASK (((FL_USER19-1)&~(FL_USER0-1))|FL_USER19)
5002 #define THREAD_SHIELD_WAITING_SHIFT (FL_USHIFT)
5003 #define THREAD_SHIELD_WAITING_MAX (THREAD_SHIELD_WAITING_MASK>>THREAD_SHIELD_WAITING_SHIFT)
5004 STATIC_ASSERT(THREAD_SHIELD_WAITING_MAX, THREAD_SHIELD_WAITING_MAX <= UINT_MAX);
5005 static inline unsigned int
5006 rb_thread_shield_waiting(
VALUE b)
5008 return ((
RBASIC(b)->flags&THREAD_SHIELD_WAITING_MASK)>>THREAD_SHIELD_WAITING_SHIFT);
5012 rb_thread_shield_waiting_inc(
VALUE b)
5014 unsigned int w = rb_thread_shield_waiting(b);
5016 if (w > THREAD_SHIELD_WAITING_MAX)
5018 RBASIC(b)->flags &= ~THREAD_SHIELD_WAITING_MASK;
5019 RBASIC(b)->flags |= ((
VALUE)w << THREAD_SHIELD_WAITING_SHIFT);
5023 rb_thread_shield_waiting_dec(
VALUE b)
5025 unsigned int w = rb_thread_shield_waiting(b);
5028 RBASIC(b)->flags &= ~THREAD_SHIELD_WAITING_MASK;
5029 RBASIC(b)->flags |= ((
VALUE)w << THREAD_SHIELD_WAITING_SHIFT);
5033 rb_thread_shield_new(
void)
5035 VALUE thread_shield = thread_shield_alloc(rb_cThreadShield);
5037 return thread_shield;
5041 rb_thread_shield_owned(
VALUE self)
5043 VALUE mutex = GetThreadShieldPtr(
self);
5044 if (!mutex)
return false;
5048 return m->fiber == GET_EC()->fiber_ptr;
5060 rb_thread_shield_wait(
VALUE self)
5062 VALUE mutex = GetThreadShieldPtr(
self);
5065 if (!mutex)
return Qfalse;
5066 m = mutex_ptr(mutex);
5067 if (m->fiber == GET_EC()->fiber_ptr)
return Qnil;
5068 rb_thread_shield_waiting_inc(
self);
5070 rb_thread_shield_waiting_dec(
self);
5073 return rb_thread_shield_waiting(
self) > 0 ?
Qnil :
Qfalse;
5077 thread_shield_get_mutex(
VALUE self)
5079 VALUE mutex = GetThreadShieldPtr(
self);
5089 rb_thread_shield_release(
VALUE self)
5091 VALUE mutex = thread_shield_get_mutex(
self);
5093 return RBOOL(rb_thread_shield_waiting(
self) > 0);
5100 rb_thread_shield_destroy(
VALUE self)
5102 VALUE mutex = thread_shield_get_mutex(
self);
5105 return RBOOL(rb_thread_shield_waiting(
self) > 0);
5111 return th->ec->local_storage_recursive_hash;
5117 th->ec->local_storage_recursive_hash = hash;
5129 recursive_list_access(
VALUE sym)
5132 VALUE hash = threadptr_recursive_hash(th);
5135 hash = rb_ident_hash_new();
5136 threadptr_recursive_hash_set(th, hash);
5143 list = rb_ident_hash_new();
5158 #if SIZEOF_LONG == SIZEOF_VOIDP
5159 #define OBJ_ID_EQL(obj_id, other) ((obj_id) == (other))
5160 #elif SIZEOF_LONG_LONG == SIZEOF_VOIDP
5161 #define OBJ_ID_EQL(obj_id, other) (RB_BIGNUM_TYPE_P((obj_id)) ? \
5162 rb_big_eql((obj_id), (other)) : ((obj_id) == (other)))
5166 if (UNDEF_P(pair_list))
5168 if (paired_obj_id) {
5170 if (!OBJ_ID_EQL(paired_obj_id, pair_list))
5203 VALUE other_paired_obj = pair_list;
5225 if (UNDEF_P(pair_list)) {
5229 rb_hash_delete_entry(pair_list, paired_obj);
5235 rb_hash_delete_entry(list, obj);
5251 return (*p->func)(p->obj, p->arg, FALSE);
5272 p.list = recursive_list_access(sym);
5276 outermost = outer && !recursive_check(p.list,
ID2SYM(recursive_key), 0);
5278 if (recursive_check(p.list, p.obj, pairid)) {
5279 if (outer && !outermost) {
5282 return (*func)(obj, arg, TRUE);
5285 enum ruby_tag_type state;
5290 recursive_push(p.list,
ID2SYM(recursive_key), 0);
5291 recursive_push(p.list, p.obj, p.pairid);
5292 result = rb_catch_protect(p.list, exec_recursive_i, (
VALUE)&p, &state);
5293 if (!recursive_pop(p.list, p.obj, p.pairid))
goto invalid;
5294 if (!recursive_pop(p.list,
ID2SYM(recursive_key), 0))
goto invalid;
5295 if (state != TAG_NONE) EC_JUMP_TAG(GET_EC(), state);
5296 if (result == p.list) {
5297 result = (*func)(obj, arg, TRUE);
5302 recursive_push(p.list, p.obj, p.pairid);
5303 EC_PUSH_TAG(GET_EC());
5304 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
5305 ret = (*func)(obj, arg, FALSE);
5308 if (!recursive_pop(p.list, p.obj, p.pairid)) {
5311 if (state != TAG_NONE) EC_JUMP_TAG(GET_EC(), state);
5320 "for %+"PRIsVALUE
" in %+"PRIsVALUE,
5362 return exec_recursive(func, obj, 0, arg, 1, mid);
5386 rb_thread_backtrace_m(
int argc,
VALUE *argv,
VALUE thval)
5388 return rb_vm_thread_backtrace(argc, argv, thval);
5403 rb_thread_backtrace_locations_m(
int argc,
VALUE *argv,
VALUE thval)
5405 return rb_vm_thread_backtrace_locations(argc, argv, thval);
5409 Init_Thread_Mutex(
void)
5499 rb_vm_register_special_exception(ruby_error_stream_closed,
rb_eIOError,
5500 "stream closed in another thread");
5510 th->thgroup = th->ractor->thgroup_default =
rb_obj_alloc(cThGroup);
5521 #ifdef HAVE_PTHREAD_NP_H
5522 VM_ASSERT(TH_SCHED(th)->running == th);
5529 th->pending_interrupt_queue_checked = 0;
5534 rb_thread_create_timer_thread();
5550 #ifdef NON_SCALAR_THREAD_ID
5551 #define thread_id_str(th) (NULL)
5553 #define thread_id_str(th) ((void *)(uintptr_t)(th)->nt->thread_id)
5562 rb_str_catf(msg,
"\n%d threads, %d sleeps current:%p main thread:%p\n",
5563 rb_ractor_living_thread_num(r), rb_ractor_sleeper_thread_num(r),
5564 (
void *)GET_THREAD(), (
void *)r->threads.main);
5566 ccan_list_for_each(&r->threads.set, th, lt_node) {
5567 rb_str_catf(msg,
"* %+"PRIsVALUE
"\n rb_thread_t:%p "
5569 th->self, (
void *)th, th->nt ? thread_id_str(th) :
"N/A", th->ec->interrupt_flag);
5571 if (th->locking_mutex) {
5572 rb_mutex_t *mutex = mutex_ptr(th->locking_mutex);
5574 (
void *)mutex->fiber, rb_mutex_num_waiting(mutex));
5580 rb_str_catf(msg,
"\n depended by: tb_thread_id:%p", (
void *)list->thread);
5593 if (GET_THREAD()->vm->thread_ignore_deadlock)
return;
5595 #ifdef RUBY_THREAD_PTHREAD_H
5596 if (r->threads.sched.readyq_cnt > 0)
return;
5599 int sleeper_num = rb_ractor_sleeper_thread_num(r);
5600 int ltnum = rb_ractor_living_thread_num(r);
5602 if (ltnum > sleeper_num)
return;
5603 if (ltnum < sleeper_num)
rb_bug(
"sleeper must not be more than vm_living_thread_num(vm)");
5608 ccan_list_for_each(&r->threads.set, th, lt_node) {
5609 if (th->status != THREAD_STOPPED_FOREVER || RUBY_VM_INTERRUPTED(th->ec)) {
5612 else if (th->locking_mutex) {
5613 rb_mutex_t *mutex = mutex_ptr(th->locking_mutex);
5614 if (mutex->fiber == th->ec->fiber_ptr || (!mutex->fiber && !ccan_list_empty(&mutex->waitq))) {
5625 argv[1] =
rb_str_new2(
"No live threads left. Deadlock?");
5626 debug_deadlock_check(r, argv[1]);
5627 rb_ractor_sleeper_threads_dec(GET_RACTOR());
5628 rb_threadptr_raise(r->threads.main, 2, argv);
5635 rb_vm_memsize_waiting_fds(
struct ccan_list_head *waiting_fds)
5640 ccan_list_for_each(waiting_fds, waitfd, wfd_node) {
5651 VALUE coverage = rb_iseq_coverage(cfp->iseq);
5659 if (GET_VM()->coverage_mode & COVERAGE_TARGET_ONESHOT_LINES) {
5660 rb_iseq_clear_event_flags(cfp->iseq, cfp->pc - ISEQ_BODY(cfp->iseq)->iseq_encoded - 1, RUBY_EVENT_COVERAGE_LINE);
5681 VALUE coverage = rb_iseq_coverage(cfp->iseq);
5685 long pc = cfp->pc - ISEQ_BODY(cfp->iseq)->iseq_encoded - 1;
5700 VALUE path, beg_pos_lineno, beg_pos_column, end_pos_lineno, end_pos_column;
5702 if (!me->def)
return NULL;
5705 switch (me->def->type) {
5706 case VM_METHOD_TYPE_ISEQ: {
5709 path = rb_iseq_path(iseq);
5710 beg_pos_lineno =
INT2FIX(loc->code_location.beg_pos.lineno);
5711 beg_pos_column =
INT2FIX(loc->code_location.beg_pos.column);
5712 end_pos_lineno =
INT2FIX(loc->code_location.end_pos.lineno);
5713 end_pos_column =
INT2FIX(loc->code_location.end_pos.column);
5716 case VM_METHOD_TYPE_BMETHOD: {
5717 const rb_iseq_t *iseq = rb_proc_get_iseq(me->def->body.bmethod.proc, 0);
5720 rb_iseq_check(iseq);
5721 path = rb_iseq_path(iseq);
5722 loc = &ISEQ_BODY(iseq)->location;
5723 beg_pos_lineno =
INT2FIX(loc->code_location.beg_pos.lineno);
5724 beg_pos_column =
INT2FIX(loc->code_location.beg_pos.column);
5725 end_pos_lineno =
INT2FIX(loc->code_location.end_pos.lineno);
5726 end_pos_column =
INT2FIX(loc->code_location.end_pos.column);
5731 case VM_METHOD_TYPE_ALIAS:
5732 me = me->def->body.alias.original_me;
5734 case VM_METHOD_TYPE_REFINED:
5735 me = me->def->body.refined.orig_me;
5736 if (!me)
return NULL;
5747 if (resolved_location) {
5748 resolved_location[0] = path;
5749 resolved_location[1] = beg_pos_lineno;
5750 resolved_location[2] = beg_pos_column;
5751 resolved_location[3] = end_pos_lineno;
5752 resolved_location[4] = end_pos_column;
5766 me = rb_resolve_me_location(me, 0);
5777 rb_get_coverages(
void)
5779 return GET_VM()->coverages;
5783 rb_get_coverage_mode(
void)
5785 return GET_VM()->coverage_mode;
5789 rb_set_coverages(
VALUE coverages,
int mode,
VALUE me2counter)
5791 GET_VM()->coverages = coverages;
5792 GET_VM()->me2counter = me2counter;
5793 GET_VM()->coverage_mode = mode;
5797 rb_resume_coverages(
void)
5799 int mode = GET_VM()->coverage_mode;
5800 VALUE me2counter = GET_VM()->me2counter;
5801 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);
5802 if (mode & COVERAGE_TARGET_BRANCHES) {
5803 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);
5805 if (mode & COVERAGE_TARGET_METHODS) {
5811 rb_suspend_coverages(
void)
5814 if (GET_VM()->coverage_mode & COVERAGE_TARGET_BRANCHES) {
5817 if (GET_VM()->coverage_mode & COVERAGE_TARGET_METHODS) {
5824 rb_reset_coverages(
void)
5826 rb_clear_coverages();
5827 rb_iseq_remove_coverage_all();
5828 GET_VM()->coverages =
Qfalse;
5832 rb_default_coverage(
int n)
5834 VALUE coverage = rb_ary_hidden_new_fill(3);
5836 int mode = GET_VM()->coverage_mode;
5838 if (mode & COVERAGE_TARGET_LINES) {
5841 RARRAY_ASET(coverage, COVERAGE_INDEX_LINES, lines);
5843 if (mode & COVERAGE_TARGET_BRANCHES) {
5844 branches = rb_ary_hidden_new_fill(2);
5872 RARRAY_ASET(coverage, COVERAGE_INDEX_BRANCHES, branches);
5878 uninterruptible_exit(
VALUE v)
5881 rb_ary_pop(cur_th->pending_interrupt_mask_stack);
5883 cur_th->pending_interrupt_queue_checked = 0;
5884 if (!rb_threadptr_pending_interrupt_empty_p(cur_th)) {
5885 RUBY_VM_SET_INTERRUPT(cur_th->ec);
5893 VALUE interrupt_mask = rb_ident_hash_new();
5898 rb_ary_push(cur_th->pending_interrupt_mask_stack, interrupt_mask);
5902 RUBY_VM_CHECK_INTS(cur_th->ec);
5909 VM_ASSERT(th->specific_storage == NULL);
5911 if (UNLIKELY(specific_key_count > 0)) {
5912 th->specific_storage =
ZALLOC_N(
void *, RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX);
5916 rb_internal_thread_specific_key_t
5921 if (specific_key_count == 0 && vm->ractor.cnt > 1) {
5922 rb_raise(
rb_eThreadError,
"The first rb_internal_thread_specific_key_create() is called with multiple ractors");
5924 else if (specific_key_count > RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX) {
5925 rb_raise(
rb_eThreadError,
"rb_internal_thread_specific_key_create() is called more than %d times", RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX);
5928 rb_internal_thread_specific_key_t key = specific_key_count++;
5935 ccan_list_for_each(&cr->threads.set, th, lt_node) {
5936 thread_specific_storage_alloc(th);
5949 VM_ASSERT(rb_thread_ptr(thread_val) == th);
5950 VM_ASSERT(key < RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX);
5951 VM_ASSERT(th->specific_storage);
5953 return th->specific_storage[key];
5962 VM_ASSERT(rb_thread_ptr(thread_val) == th);
5963 VM_ASSERT(key < RB_INTERNAL_THREAD_SPECIFIC_KEY_MAX);
5964 VM_ASSERT(th->specific_storage);
5966 th->specific_storage[key] = data;
5972 struct ccan_list_node node;
5974 rb_interrupt_exec_func_t *func;
5976 enum rb_interrupt_exec_flag flags;
5980 rb_threadptr_interrupt_exec_task_mark(
rb_thread_t *th)
5984 ccan_list_for_each(&th->interrupt_exec_tasks, task, node) {
5985 if (task->flags & rb_interrupt_exec_flag_value_data) {
5994 rb_threadptr_interrupt_exec(
rb_thread_t *th, rb_interrupt_exec_func_t *func,
void *data,
enum rb_interrupt_exec_flag flags)
6006 ccan_list_add_tail(&th->interrupt_exec_tasks, &task->node);
6007 threadptr_interrupt_locked(th,
true);
6025 (*task->func)(task->data);
6049 rb_interrupt_exec_func_t *func;
6054 interrupt_ractor_new_thread_func(
void *data)
6064 interrupt_ractor_func(
void *data)
6074 rb_interrupt_exec_func_t *func,
void *data,
enum rb_interrupt_exec_flag flags)
6081 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_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.
void rb_define_method(VALUE klass, const char *name, VALUE(*func)(ANYARGS), int argc)
Defines a method.
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_raise(VALUE exc, const char *fmt,...)
Exception entry point.
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
void rb_bug(const char *fmt,...)
Interpreter panic switch.
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_eArgError
ArgumentError exception.
VALUE rb_eException
Mother of all exceptions.
VALUE rb_ensure(VALUE(*b_proc)(VALUE), VALUE data1, VALUE(*e_proc)(VALUE), VALUE data2)
An equivalent to ensure clause.
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 bool rb_enc_asciicompat(rb_encoding *enc)
Queries if the passed encoding is in some sense compatible with ASCII.
rb_encoding * rb_enc_get(VALUE obj)
Identical to rb_enc_get_index(), except the return type.
static const char * rb_enc_name(rb_encoding *enc)
Queries the (canonical) name of the passed encoding.
void rb_gc_mark(VALUE obj)
Marks an object.
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...
VALUE rb_fiber_current(void)
Queries the fiber which is calling this function.
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
VALUE rb_make_exception(int argc, const VALUE *argv)
Constructs an exception object from the list of arguments, in a manner similar to Ruby's raise.
void rb_obj_call_init_kw(VALUE, int, const VALUE *, int)
Identical to rb_obj_call_init(), except you can specify how to handle the last element of the given a...
void rb_hash_foreach(VALUE hash, int(*func)(VALUE key, VALUE val, VALUE arg), VALUE arg)
Iterates over a hash.
VALUE rb_hash_lookup2(VALUE hash, VALUE key, VALUE def)
Identical to rb_hash_lookup(), except you can specify what to return on misshits.
VALUE rb_hash_aref(VALUE hash, VALUE key)
Queries the given key in the given hash table.
VALUE rb_hash_aset(VALUE hash, VALUE key, VALUE val)
Inserts or replaces ("upsert"s) the objects into the given hash table.
VALUE rb_hash_lookup(VALUE hash, VALUE key)
Identical to rb_hash_aref(), except it always returns RUBY_Qnil for misshits.
VALUE rb_hash_new(void)
Creates a new, empty hash object.
VALUE rb_memory_id(VALUE obj)
Identical to rb_obj_id(), except it hesitates from allocating a new instance of rb_cInteger.
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.
VALUE rb_str_new_cstr(const char *ptr)
Identical to rb_str_new(), except it assumes the passed pointer is a pointer to a C string.
VALUE rb_str_cat_cstr(VALUE dst, const char *src)
Identical to rb_str_cat(), 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.
VALUE rb_thread_create(VALUE(*f)(void *g), void *g)
Creates a Ruby thread that is backended by a C function.
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(), except it takes an instance of rb_cString.
void rb_define_const(VALUE klass, const char *name, VALUE val)
Defines a Ruby level constant under a namespace.
VALUE rb_eIOTimeoutError
Indicates that a timeout has occurred while performing an IO operation.
char * ptr
Pointer to the underlying memory region, of at least capa bytes.
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.
#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_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_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_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.
VALUE rb_sprintf(const char *fmt,...)
Ruby's extended sprintf(3).
VALUE rb_str_catf(VALUE dst, const char *fmt,...)
Identical to rb_sprintf(), except it renders the output to the specified object rather than creating ...
#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.
static fd_set * rb_fd_ptr(const rb_fdset_t *f)
Raw pointer to fd_set.
int rb_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.
int rb_fd_isset(int fd, const rb_fdset_t *f)
Queries if the given FD is in the given set.
void rb_fd_clr(int fd, rb_fdset_t *f)
Releases a specific FD from the given fdset.
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.
void rb_fd_zero(rb_fdset_t *f)
Wipes out the current set of FDs.
#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.
#define rb_fd_init
Initialises the :given :rb_fdset_t.
#define rb_fd_set
Sets the given fd to 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...
int rb_errno(void)
Identical to system errno.
void rb_errno_set(int err)
Set the errno.
#define errno
Ractor-aware version of errno.
int ruby_native_thread_p(void)
Queries if the thread which calls this function is a ruby's thread.
int ruby_snprintf(char *str, size_t n, char const *fmt,...)
Our own locale-insensitive version of snprintf(3).
#define RB_PASS_CALLED_KEYWORDS
Pass keywords if current method is called with keywords, useful for argument delegation.
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.
void ruby_xfree(void *ptr)
Deallocates a storage instance.