12#ifdef THREAD_SYSTEM_DEPENDENT_IMPLEMENTATION
16#define TIME_QUANTUM_USEC (10 * 1000)
17#define RB_CONDATTR_CLOCK_MONOTONIC 1
21#define native_thread_yield() Sleep(0)
22#define unregister_ubf_list(th)
23#define ubf_wakeup_all_threads() do {} while (0)
24#define ubf_threads_empty() (1)
25#define ubf_timer_disarm() do {} while (0)
26#define ubf_list_atfork() do {} while (0)
28static volatile DWORD ruby_native_thread_key = TLS_OUT_OF_INDEXES;
30static int w32_wait_events(HANDLE *events,
int count, DWORD timeout,
rb_thread_t *th);
32rb_internal_thread_event_hook_t *
48w32_error(const
char *func)
51 DWORD err = GetLastError();
52 if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
53 FORMAT_MESSAGE_FROM_SYSTEM |
54 FORMAT_MESSAGE_IGNORE_INSERTS,
57 MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
58 (LPTSTR) & lpMsgBuf, 0, NULL) == 0)
59 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
60 FORMAT_MESSAGE_FROM_SYSTEM |
61 FORMAT_MESSAGE_IGNORE_INSERTS,
64 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
65 (LPTSTR) & lpMsgBuf, 0, NULL);
66 rb_bug(
"%s: %s", func, (
char*)lpMsgBuf);
70#define W32_EVENT_DEBUG 0
73#define w32_event_debug printf
75#define w32_event_debug if (0) printf
79w32_mutex_lock(HANDLE lock,
bool try)
84 w32_event_debug(
"lock:%p\n", lock);
86 result = w32_wait_events(&lock, 1,
try ? 0 : INFINITE, 0);
90 w32_event_debug(
"locked lock:%p\n", lock);
93 case WAIT_OBJECT_0 + 1:
96 w32_event_debug(
"interrupted lock:%p\n", lock);
100 w32_event_debug(
"timeout locK:%p\n", lock);
104 rb_bug(
"win32_mutex_lock: WAIT_ABANDONED");
108 rb_bug(
"win32_mutex_lock: unknown result (%ld)", result);
116w32_mutex_create(
void)
118 HANDLE lock = CreateMutex(NULL, FALSE, NULL);
120 w32_error(
"rb_native_mutex_initialize");
130 w32_mutex_lock(sched->lock,
false);
131 if (GVL_DEBUG) fprintf(stderr,
"gvl acquire (%p): acquire\n", th);
137 ReleaseMutex(sched->lock);
143 thread_sched_to_waiting(sched);
144 native_thread_yield();
145 thread_sched_to_running(sched, th);
151 if (GVL_DEBUG) fprintf(stderr,
"sched init\n");
152 sched->lock = w32_mutex_create();
159 if (GVL_DEBUG) fprintf(stderr,
"sched destroy\n");
160 CloseHandle(sched->lock);
165ruby_thread_from_native(
void)
167 return TlsGetValue(ruby_native_thread_key);
174 rb_ractor_set_current_ec(th->ractor, th->ec);
176 return TlsSetValue(ruby_native_thread_key, th);
182 if ((ruby_current_ec_key = TlsAlloc()) == TLS_OUT_OF_INDEXES) {
183 rb_bug(
"TlsAlloc() for ruby_current_ec_key fails");
185 if ((ruby_native_thread_key = TlsAlloc()) == TLS_OUT_OF_INDEXES) {
186 rb_bug(
"TlsAlloc() for ruby_native_thread_key fails");
191 ruby_thread_set_native(main_th);
192 main_th->nt->interrupt_event = CreateEvent(0, TRUE, FALSE, 0);
194 DuplicateHandle(GetCurrentProcess(),
197 &main_th->nt->thread_id, 0, FALSE, DUPLICATE_SAME_ACCESS);
199 RUBY_DEBUG_LOG(
"initial thread th:%u thid:%p, event: %p",
200 rb_th_serial(main_th),
201 main_th->nt->thread_id,
202 main_th->nt->interrupt_event);
206w32_wait_events(HANDLE *events,
int count, DWORD timeout,
rb_thread_t *th)
208 HANDLE *targets = events;
210 const int initcount = count;
213 w32_event_debug(
"events:%p, count:%d, timeout:%ld, th:%u\n",
214 events, count, timeout, th ? rb_th_serial(th) : UINT_MAX);
216 if (th && (intr = th->nt->interrupt_event)) {
217 if (ResetEvent(intr) && (!RUBY_VM_INTERRUPTED(th->ec) || SetEvent(intr))) {
218 targets =
ALLOCA_N(HANDLE, count + 1);
219 memcpy(targets, events,
sizeof(HANDLE) * count);
221 targets[count++] = intr;
222 w32_event_debug(
"handle:%p (count:%d, intr)\n", intr, count);
224 else if (intr == th->nt->interrupt_event) {
225 w32_error(
"w32_wait_events");
229 w32_event_debug(
"WaitForMultipleObjects start count:%d\n", count);
230 ret = WaitForMultipleObjects(count, targets, FALSE, timeout);
231 w32_event_debug(
"WaitForMultipleObjects end ret:%lu\n", ret);
233 if (ret == (DWORD)(WAIT_OBJECT_0 + initcount) && th) {
236 if (ret == WAIT_FAILED && W32_EVENT_DEBUG) {
239 for (i = 0; i < count; i++) {
240 w32_event_debug(
"i:%d %s\n", i, GetHandleInformation(targets[i], &dmy) ?
"OK" :
"NG");
246static void ubf_handle(
void *ptr);
247#define ubf_select ubf_handle
250rb_w32_wait_events_blocking(HANDLE *events,
int num, DWORD timeout)
252 return w32_wait_events(events, num, timeout, ruby_thread_from_native());
256rb_w32_wait_events(HANDLE *events,
int num, DWORD timeout)
261 BLOCKING_REGION(th, ret = rb_w32_wait_events_blocking(events, num, timeout),
262 ubf_handle, ruby_thread_from_native(), FALSE);
267w32_close_handle(HANDLE handle)
269 if (CloseHandle(handle) == 0) {
270 w32_error(
"w32_close_handle");
275w32_resume_thread(HANDLE handle)
277 if (ResumeThread(handle) == (DWORD)-1) {
278 w32_error(
"w32_resume_thread");
283#define HAVE__BEGINTHREADEX 1
285#undef HAVE__BEGINTHREADEX
288#ifdef HAVE__BEGINTHREADEX
289#define start_thread (HANDLE)_beginthreadex
290#define thread_errno errno
291typedef unsigned long (__stdcall *w32_thread_start_func)(
void*);
293#define start_thread CreateThread
294#define thread_errno rb_w32_map_errno(GetLastError())
295typedef LPTHREAD_START_ROUTINE w32_thread_start_func;
299w32_create_thread(DWORD stack_size, w32_thread_start_func func,
void *val)
301 return start_thread(0, stack_size, func, val, CREATE_SUSPENDED | STACK_SIZE_PARAM_IS_A_RESERVATION, 0);
305rb_w32_sleep(
unsigned long msec)
307 return w32_wait_events(0, 0, msec, ruby_thread_from_native());
311rb_w32_Sleep(
unsigned long msec)
316 BLOCKING_REGION(th, ret = rb_w32_sleep(msec),
317 ubf_handle, ruby_thread_from_native(), FALSE);
322hrtime2msec(rb_hrtime_t hrt)
324 return (DWORD)hrt / (DWORD)RB_HRTIME_PER_MSEC;
330 const volatile DWORD msec = rel ? hrtime2msec(*rel) : INFINITE;
332 THREAD_BLOCKING_BEGIN(th);
337 th->unblock.func = ubf_handle;
338 th->unblock.arg = th;
341 if (RUBY_VM_INTERRUPTED(th->ec)) {
345 RUBY_DEBUG_LOG(
"start msec:%lu", msec);
346 ret = w32_wait_events(0, 0, msec, th);
347 RUBY_DEBUG_LOG(
"done ret:%lu", ret);
352 th->unblock.func = 0;
356 THREAD_BLOCKING_END(th);
362#ifdef USE_WIN32_MUTEX
363 w32_mutex_lock(lock->mutex,
false);
365 EnterCriticalSection(&lock->crit);
372#ifdef USE_WIN32_MUTEX
373 return w32_mutex_lock(lock->mutex,
true);
375 return TryEnterCriticalSection(&lock->crit) == 0 ? EBUSY : 0;
382#ifdef USE_WIN32_MUTEX
383 RUBY_DEBUG_LOG(
"lock:%p", lock->mutex);
384 ReleaseMutex(lock->mutex);
386 LeaveCriticalSection(&lock->crit);
393#ifdef USE_WIN32_MUTEX
394 lock->mutex = w32_mutex_create();
397 InitializeCriticalSection(&lock->crit);
404#ifdef USE_WIN32_MUTEX
405 w32_close_handle(lock->mutex);
407 DeleteCriticalSection(&lock->crit);
411struct cond_event_entry {
412 struct cond_event_entry* next;
413 struct cond_event_entry* prev;
421 struct cond_event_entry *e = cond->next;
422 struct cond_event_entry *head = (
struct cond_event_entry*)cond;
425 struct cond_event_entry *next = e->next;
426 struct cond_event_entry *prev = e->prev;
430 e->next = e->prev = e;
440 struct cond_event_entry *e = cond->next;
441 struct cond_event_entry *head = (
struct cond_event_entry*)cond;
444 struct cond_event_entry *next = e->next;
445 struct cond_event_entry *prev = e->prev;
451 e->next = e->prev = e;
461 struct cond_event_entry entry;
462 struct cond_event_entry *head = (
struct cond_event_entry*)cond;
464 entry.event = CreateEvent(0, FALSE, FALSE, 0);
468 entry.prev = head->prev;
469 head->prev->next = &entry;
474 r = WaitForSingleObject(entry.event, msec);
475 if ((r != WAIT_OBJECT_0) && (r != WAIT_TIMEOUT)) {
476 rb_bug(
"rb_native_cond_wait: WaitForSingleObject returns %lu", r);
481 entry.prev->next = entry.next;
482 entry.next->prev = entry.prev;
484 w32_close_handle(entry.event);
485 return (r == WAIT_OBJECT_0) ? 0 : ETIMEDOUT;
491 native_cond_timedwait_ms(cond, mutex, INFINITE);
495abs_timespec_to_timeout_ms(
const struct timespec *ts)
500 gettimeofday(&now, NULL);
501 tv.tv_sec = ts->tv_sec;
502 tv.tv_usec = ts->tv_nsec / 1000;
504 if (!rb_w32_time_subtract(&tv, &now))
507 return (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
513 unsigned long timeout_ms;
515 timeout_ms = abs_timespec_to_timeout_ms(ts);
519 return native_cond_timedwait_ms(cond, mutex, timeout_ms);
528 .tv_sec = msec / 1000,
529 .tv_nsec = (msec % 1000) * 1000 * 1000,
531 struct timespec ts = native_cond_timeout(cond, rel);
532 native_cond_timedwait(cond, mutex, &ts);
543 ret = gettimeofday(&tv, 0);
546 now.tv_sec = tv.tv_sec;
547 now.tv_nsec = tv.tv_usec * 1000;
549 timeout.tv_sec = now.tv_sec;
550 timeout.tv_nsec = now.tv_nsec;
551 timeout.tv_sec += timeout_rel.tv_sec;
552 timeout.tv_nsec += timeout_rel.tv_nsec;
554 if (timeout.tv_nsec >= 1000*1000*1000) {
556 timeout.tv_nsec -= 1000*1000*1000;
559 if (timeout.tv_sec < now.tv_sec)
560 timeout.tv_sec = TIMET_MAX;
568 cond->next = (
struct cond_event_entry *)cond;
569 cond->prev = (
struct cond_event_entry *)cond;
583#define CHECK_ERR(expr) \
584 {if (!(expr)) {rb_bug("err: %lu - %s", GetLastError(), #expr);}}
588COMPILER_WARNING_IGNORED(-Wmaybe-uninitialized)
591query_memory_basic_info(PMEMORY_BASIC_INFORMATION mi)
593 return VirtualQuery(mi, mi,
sizeof(*mi));
600 MEMORY_BASIC_INFORMATION mi;
604 CHECK_ERR(query_memory_basic_info(&mi));
605 base = mi.AllocationBase;
606 end = mi.BaseAddress;
607 end += mi.RegionSize;
610 if (space > 1024*1024) space = 1024*1024;
611 th->ec->machine.stack_start = (
VALUE *)end - 1;
612 th->ec->machine.stack_maxsize = size - space;
615#ifndef InterlockedExchangePointer
616#define InterlockedExchangePointer(t, v) \
617 (void *)InterlockedExchange((long *)(t), (long)(v))
622 HANDLE intr = InterlockedExchangePointer(&th->nt->interrupt_event, 0);
623 RUBY_DEBUG_LOG(
"close handle intr:%p, thid:%p\n", intr, th->nt->thread_id);
624 w32_close_handle(intr);
627static unsigned long __stdcall
628thread_start_func_1(
void *th_ptr)
631 volatile HANDLE thread_id = th->nt->thread_id;
633 native_thread_init_stack(th);
634 th->nt->interrupt_event = CreateEvent(0, TRUE, FALSE, 0);
637 RUBY_DEBUG_LOG(
"thread created th:%u, thid: %p, event: %p",
638 rb_th_serial(th), th->nt->thread_id, th->nt->interrupt_event);
640 thread_start_func_2(th, th->ec->machine.stack_start);
642 w32_close_handle(thread_id);
643 RUBY_DEBUG_LOG(
"thread deleted th:%u", rb_th_serial(th));
650 const size_t stack_size = th->vm->default_params.thread_machine_stack_size + th->vm->default_params.thread_vm_stack_size;
652 th->nt->thread_id = w32_create_thread(stack_size, thread_start_func_1, th);
654 if ((th->nt->thread_id) == 0) {
658 w32_resume_thread(th->nt->thread_id);
660 if (USE_RUBY_DEBUG_LOG) {
662 RUBY_DEBUG_LOG(
"th:%u thid:%p intr:%p), stack size: %"PRIuSIZE
"",
663 rb_th_serial(th), th->nt->thread_id,
664 th->nt->interrupt_event, stack_size);
670native_thread_join(HANDLE th)
672 w32_wait_events(&th, 1, INFINITE, 0);
675#if USE_NATIVE_THREAD_PRIORITY
680 int priority = th->priority;
681 if (th->priority > 0) {
682 priority = THREAD_PRIORITY_ABOVE_NORMAL;
684 else if (th->priority < 0) {
685 priority = THREAD_PRIORITY_BELOW_NORMAL;
688 priority = THREAD_PRIORITY_NORMAL;
691 SetThreadPriority(th->nt->thread_id, priority);
701 fd_set *r = NULL, *w = NULL, *e = NULL;
704 r = rb_fd_ptr(readfds);
708 w = rb_fd_ptr(writefds);
712 e = rb_fd_ptr(exceptfds);
714 return rb_w32_select_with_thread(n, r, w, e, timeout, th);
721 return w32_wait_events(0, 0, 0, th);
728 RUBY_DEBUG_LOG(
"th:%u\n", rb_th_serial(th));
730 if (!SetEvent(th->nt->interrupt_event)) {
731 w32_error(
"ubf_handle");
735int rb_w32_set_thread_description(HANDLE th,
const WCHAR *name);
736int rb_w32_set_thread_description_str(HANDLE th,
VALUE name);
737#define native_set_another_thread_name rb_w32_set_thread_description_str
743#define TIMER_THREAD_CREATED_P() (timer_thread.id != 0)
745static unsigned long __stdcall
746timer_thread_func(
void *dummy)
749 RUBY_DEBUG_LOG(
"start");
750 rb_w32_set_thread_description(GetCurrentThread(), L
"ruby-timer-thread");
751 while (WaitForSingleObject(timer_thread.lock,
752 TIME_QUANTUM_USEC/1000) == WAIT_TIMEOUT) {
754 ruby_sigchld_handler(vm);
755 rb_threadptr_check_signal(vm->ractor.main_thread);
757 RUBY_DEBUG_LOG(
"end");
762rb_thread_wakeup_timer_thread(
int sig)
768rb_thread_start_unblock_thread(
void)
774rb_thread_create_timer_thread(
void)
776 if (timer_thread.id == 0) {
777 if (!timer_thread.lock) {
778 timer_thread.lock = CreateEvent(0, TRUE, FALSE, 0);
780 timer_thread.id = w32_create_thread(1024 + (USE_RUBY_DEBUG_LOG ? BUFSIZ : 0),
781 timer_thread_func, 0);
782 w32_resume_thread(timer_thread.id);
787native_stop_timer_thread(
void)
789 int stopped = --system_working <= 0;
791 SetEvent(timer_thread.lock);
792 native_thread_join(timer_thread.id);
793 CloseHandle(timer_thread.lock);
794 timer_thread.lock = 0;
800native_reset_timer_thread(
void)
802 if (timer_thread.id) {
803 CloseHandle(timer_thread.id);
809ruby_stack_overflowed_p(
const rb_thread_t *th,
const void *addr)
811 return rb_ec_raised_p(th->ec, RAISED_STACKOVERFLOW);
814#if defined(__MINGW32__)
816rb_w32_stack_overflow_handler(
struct _EXCEPTION_POINTERS *exception)
818 if (exception->ExceptionRecord->ExceptionCode == EXCEPTION_STACK_OVERFLOW) {
819 rb_ec_raised_set(GET_EC(), RAISED_STACKOVERFLOW);
822 return EXCEPTION_CONTINUE_SEARCH;
826#ifdef RUBY_ALLOCA_CHKSTK
828ruby_alloca_chkstk(
size_t len,
void *sp)
832 if (!rb_ec_raised_p(ec, RAISED_STACKOVERFLOW)) {
833 rb_ec_raised_set(ec, RAISED_STACKOVERFLOW);
851NORETURN(
void rb_sigwait_fd_put(
rb_thread_t *,
int));
855 rb_bug(
"not implemented, should not be called");
858NORETURN(
void rb_sigwait_sleep(
const rb_thread_t *,
int,
const rb_hrtime_t *));
860rb_sigwait_sleep(
const rb_thread_t *th,
int fd,
const rb_hrtime_t *rel)
862 rb_bug(
"not implemented, should not be called");
868 return GetCurrentThread();
879 DWORD tid = GetThreadId(th->nt->thread_id);
883#define USE_NATIVE_THREAD_NATIVE_THREAD_ID 1
uint32_t rb_event_flag_t
Represents event(s).
#define UNREACHABLE
Old name of RBIMPL_UNREACHABLE.
#define ULONG2NUM
Old name of RB_ULONG2NUM.
#define ZALLOC
Old name of RB_ZALLOC.
#define Qfalse
Old name of RUBY_Qfalse.
void ruby_init_stack(volatile VALUE *addr)
Set stack bottom of Ruby implementation.
size_t ruby_stack_length(VALUE **p)
Queries what Ruby thinks is the machine stack.
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
void rb_bug(const char *fmt,...)
Interpreter panic switch.
void rb_sys_fail(const char *mesg)
Converts a C errno into a Ruby exception, then raises it.
int rb_reserved_fd_p(int fd)
Queries if the given FD is reserved or not.
rb_internal_thread_event_hook_t * rb_internal_thread_add_event_hook(rb_internal_thread_event_callback func, rb_event_flag_t events, void *data)
Registers a thread event hook function.
bool rb_internal_thread_remove_event_hook(rb_internal_thread_event_hook_t *hook)
Unregister the passed hook.
#define ALLOCA_N(type, n)
#define RBIMPL_ATTR_NORETURN()
Wraps (or simulates) [[noreturn]]
#define rb_fd_resize(n, f)
Does nothing (defined for compatibility).
The data structure which wraps the fd_set bitmap used by select(2).
rb_nativethread_id_t rb_nativethread_self(void)
Queries the ID of the native thread that is calling this function.
void rb_native_mutex_lock(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_lock.
void rb_native_cond_initialize(rb_nativethread_cond_t *cond)
Fills the passed condition variable with an initial value.
int rb_native_mutex_trylock(rb_nativethread_lock_t *lock)
Identical to rb_native_mutex_lock(), except it doesn't block in case rb_native_mutex_lock() would.
void rb_native_cond_broadcast(rb_nativethread_cond_t *cond)
Signals a condition variable.
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_native_mutex_destroy(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_destroy.
void rb_native_cond_destroy(rb_nativethread_cond_t *cond)
Destroys the passed condition variable.
void rb_native_cond_signal(rb_nativethread_cond_t *cond)
Signals a condition variable.
void rb_native_cond_wait(rb_nativethread_cond_t *cond, rb_nativethread_lock_t *mutex)
Waits for the passed condition variable to be signalled.
void rb_native_cond_timedwait(rb_nativethread_cond_t *cond, rb_nativethread_lock_t *mutex, unsigned long msec)
Identical to rb_native_cond_wait(), except it additionally takes timeout in msec resolution.
uintptr_t VALUE
Type that represents a Ruby object.