Ruby 4.0.7p0 (2026-09-15 revision 229531a6cfbf07e3caef30dbac24a2a3f3fed482)
thread_win32.c
1/* -*-c-*- */
2/**********************************************************************
3
4 thread_win32.c -
5
6 $Author$
7
8 Copyright (C) 2004-2007 Koichi Sasada
9
10**********************************************************************/
11
12#ifdef THREAD_SYSTEM_DEPENDENT_IMPLEMENTATION
13
14#include "internal/sanitizers.h"
15#include <process.h>
16
17#define TIME_QUANTUM_USEC (10 * 1000)
18#define RB_CONDATTR_CLOCK_MONOTONIC 1 /* no effect */
19
20#undef Sleep
21
22#define native_thread_yield() Sleep(0)
23#define unregister_ubf_list(th)
24#define ubf_wakeup_all_threads() do {} while (0)
25#define ubf_threads_empty() (1)
26#define ubf_timer_disarm() do {} while (0)
27#define ubf_list_atfork() do {} while (0)
28
29static volatile DWORD ruby_native_thread_key = TLS_OUT_OF_INDEXES;
30
31static int w32_wait_events(HANDLE *events, int count, DWORD timeout, rb_thread_t *th);
32
33rb_internal_thread_event_hook_t *
34rb_internal_thread_add_event_hook(rb_internal_thread_event_callback callback, rb_event_flag_t internal_event, void *user_data)
35{
36 // not implemented
37 return NULL;
38}
39
40bool
41rb_internal_thread_remove_event_hook(rb_internal_thread_event_hook_t * hook)
42{
43 // not implemented
44 return false;
45}
46
48static void
49w32_error(const char *func)
50{
51 LPVOID lpMsgBuf;
52 DWORD err = GetLastError();
53 if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
54 FORMAT_MESSAGE_FROM_SYSTEM |
55 FORMAT_MESSAGE_IGNORE_INSERTS,
56 NULL,
57 err,
58 MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
59 (LPTSTR) & lpMsgBuf, 0, NULL) == 0)
60 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
61 FORMAT_MESSAGE_FROM_SYSTEM |
62 FORMAT_MESSAGE_IGNORE_INSERTS,
63 NULL,
64 err,
65 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
66 (LPTSTR) & lpMsgBuf, 0, NULL);
67 rb_bug("%s: %s", func, (char*)lpMsgBuf);
69}
70
71#define W32_EVENT_DEBUG 0
72
73#if W32_EVENT_DEBUG
74#define w32_event_debug printf
75#else
76#define w32_event_debug if (0) printf
77#endif
78
79static int
80w32_mutex_lock(HANDLE lock, bool try)
81{
82 DWORD result;
83 while (1) {
84 // RUBY_DEBUG_LOG() is not available because RUBY_DEBUG_LOG() calls it.
85 w32_event_debug("lock:%p\n", lock);
86
87 result = w32_wait_events(&lock, 1, try ? 0 : INFINITE, 0);
88 switch (result) {
89 case WAIT_OBJECT_0:
90 /* get mutex object */
91 w32_event_debug("locked lock:%p\n", lock);
92 return 0;
93
94 case WAIT_OBJECT_0 + 1:
95 /* interrupt */
96 errno = EINTR;
97 w32_event_debug("interrupted lock:%p\n", lock);
98 return 0;
99
100 case WAIT_TIMEOUT:
101 w32_event_debug("timeout locK:%p\n", lock);
102 return EBUSY;
103
104 case WAIT_ABANDONED:
105 rb_bug("win32_mutex_lock: WAIT_ABANDONED");
106 break;
107
108 default:
109 rb_bug("win32_mutex_lock: unknown result (%ld)", result);
110 break;
111 }
112 }
113 return 0;
114}
115
116static HANDLE
117w32_mutex_create(void)
118{
119 HANDLE lock = CreateMutex(NULL, FALSE, NULL);
120 if (lock == NULL) {
121 w32_error("rb_native_mutex_initialize");
122 }
123 return lock;
124}
125
126#define GVL_DEBUG 0
127
128static void
129thread_sched_to_running(struct rb_thread_sched *sched, rb_thread_t *th)
130{
131 w32_mutex_lock(sched->lock, false);
132 if (GVL_DEBUG) fprintf(stderr, "gvl acquire (%p): acquire\n", th);
133}
134
135static void
136thread_sched_to_waiting(struct rb_thread_sched *sched, rb_thread_t *th, bool yield_immediately)
137{
138 ReleaseMutex(sched->lock);
139}
140
141static void
142thread_sched_to_dead(struct rb_thread_sched *sched, rb_thread_t *th)
143{
144 thread_sched_to_waiting(sched, th, true);
145}
146
147static void
148thread_sched_yield(struct rb_thread_sched *sched, rb_thread_t *th)
149{
150 thread_sched_to_waiting(sched, th, true);
151 native_thread_yield();
152 thread_sched_to_running(sched, th);
153}
154
155void
156rb_thread_sched_init(struct rb_thread_sched *sched, bool atfork)
157{
158 if (GVL_DEBUG) fprintf(stderr, "sched init\n");
159 sched->lock = w32_mutex_create();
160}
161
162#if 0
163// per-ractor
164void
165rb_thread_sched_destroy(struct rb_thread_sched *sched)
166{
167 if (GVL_DEBUG) fprintf(stderr, "sched destroy\n");
168 CloseHandle(sched->lock);
169}
170#endif
171
172rb_thread_t *
173ruby_thread_from_native(void)
174{
175 return TlsGetValue(ruby_native_thread_key);
176}
177
178int
179ruby_thread_set_native(rb_thread_t *th)
180{
181 if (th && th->ec) {
182 rb_ractor_set_current_ec(th->ractor, th->ec);
183 }
184 return TlsSetValue(ruby_native_thread_key, th);
185}
186
187void
188Init_native_thread(rb_thread_t *main_th)
189{
190 if ((ruby_current_ec_key = TlsAlloc()) == TLS_OUT_OF_INDEXES) {
191 rb_bug("TlsAlloc() for ruby_current_ec_key fails");
192 }
193 if ((ruby_native_thread_key = TlsAlloc()) == TLS_OUT_OF_INDEXES) {
194 rb_bug("TlsAlloc() for ruby_native_thread_key fails");
195 }
196
197 // setup main thread
198
199 ruby_thread_set_native(main_th);
200 main_th->nt->interrupt_event = CreateEvent(0, TRUE, FALSE, 0);
201
202 DuplicateHandle(GetCurrentProcess(),
203 GetCurrentThread(),
204 GetCurrentProcess(),
205 &main_th->nt->thread_id, 0, FALSE, DUPLICATE_SAME_ACCESS);
206
207 RUBY_DEBUG_LOG("initial thread th:%u thid:%p, event: %p",
208 rb_th_serial(main_th),
209 main_th->nt->thread_id,
210 main_th->nt->interrupt_event);
211}
212
213void
214ruby_mn_threads_params(void)
215{
216}
217
218static int
219w32_wait_events(HANDLE *events, int count, DWORD timeout, rb_thread_t *th)
220{
221 HANDLE *targets = events;
222 HANDLE intr;
223 const int initcount = count;
224 DWORD ret;
225
226 w32_event_debug("events:%p, count:%d, timeout:%ld, th:%u\n",
227 events, count, timeout, th ? rb_th_serial(th) : UINT_MAX);
228
229 if (th && (intr = th->nt->interrupt_event)) {
230 if (ResetEvent(intr) && (!RUBY_VM_INTERRUPTED(th->ec) || SetEvent(intr))) {
231 targets = ALLOCA_N(HANDLE, count + 1);
232 memcpy(targets, events, sizeof(HANDLE) * count);
233
234 targets[count++] = intr;
235 w32_event_debug("handle:%p (count:%d, intr)\n", intr, count);
236 }
237 else if (intr == th->nt->interrupt_event) {
238 w32_error("w32_wait_events");
239 }
240 }
241
242 w32_event_debug("WaitForMultipleObjects start count:%d\n", count);
243 ret = WaitForMultipleObjects(count, targets, FALSE, timeout);
244 w32_event_debug("WaitForMultipleObjects end ret:%lu\n", ret);
245
246 if (ret == (DWORD)(WAIT_OBJECT_0 + initcount) && th) {
247 errno = EINTR;
248 }
249 if (ret == WAIT_FAILED && W32_EVENT_DEBUG) {
250 int i;
251 DWORD dmy;
252 for (i = 0; i < count; i++) {
253 w32_event_debug("i:%d %s\n", i, GetHandleInformation(targets[i], &dmy) ? "OK" : "NG");
254 }
255 }
256 return ret;
257}
258
259static void ubf_handle(void *ptr);
260#define ubf_select ubf_handle
261
262int
263rb_w32_wait_events_blocking(HANDLE *events, int num, DWORD timeout)
264{
265 return w32_wait_events(events, num, timeout, ruby_thread_from_native());
266}
267
268int
269rb_w32_wait_events(HANDLE *events, int num, DWORD timeout)
270{
271 int ret;
272 rb_thread_t *th = GET_THREAD();
273
274 BLOCKING_REGION(th, ret = rb_w32_wait_events_blocking(events, num, timeout),
275 ubf_handle, ruby_thread_from_native(), FALSE);
276 return ret;
277}
278
279static void
280w32_close_handle(HANDLE handle)
281{
282 if (CloseHandle(handle) == 0) {
283 w32_error("w32_close_handle");
284 }
285}
286
287static void
288w32_resume_thread(HANDLE handle)
289{
290 if (ResumeThread(handle) == (DWORD)-1) {
291 w32_error("w32_resume_thread");
292 }
293}
294
295#ifdef _MSC_VER
296#define HAVE__BEGINTHREADEX 1
297#else
298#undef HAVE__BEGINTHREADEX
299#endif
300
301#ifdef HAVE__BEGINTHREADEX
302#define start_thread (HANDLE)_beginthreadex
303#define thread_errno errno
304typedef unsigned long (__stdcall *w32_thread_start_func)(void*);
305#else
306#define start_thread CreateThread
307#define thread_errno rb_w32_map_errno(GetLastError())
308typedef LPTHREAD_START_ROUTINE w32_thread_start_func;
309#endif
310
311static HANDLE
312w32_create_thread(DWORD stack_size, w32_thread_start_func func, void *val)
313{
314 return start_thread(0, stack_size, func, val, CREATE_SUSPENDED | STACK_SIZE_PARAM_IS_A_RESERVATION, 0);
315}
316
317int
318rb_w32_sleep(unsigned long msec)
319{
320 return w32_wait_events(0, 0, msec, ruby_thread_from_native());
321}
322
323int WINAPI
324rb_w32_Sleep(unsigned long msec)
325{
326 int ret;
327 rb_thread_t *th = GET_THREAD();
328
329 BLOCKING_REGION(th, ret = rb_w32_sleep(msec),
330 ubf_handle, ruby_thread_from_native(), FALSE);
331 return ret;
332}
333
334static DWORD
335hrtime2msec(rb_hrtime_t hrt)
336{
337 return (DWORD)hrt / (DWORD)RB_HRTIME_PER_MSEC;
338}
339
340static void
341native_sleep(rb_thread_t *th, rb_hrtime_t *rel)
342{
343 const volatile DWORD msec = rel ? hrtime2msec(*rel) : INFINITE;
344
345 THREAD_BLOCKING_BEGIN(th);
346 {
347 DWORD ret;
348
349 rb_native_mutex_lock(&th->interrupt_lock);
350 th->unblock.func = ubf_handle;
351 th->unblock.arg = th;
352 rb_native_mutex_unlock(&th->interrupt_lock);
353
354 if (RUBY_VM_INTERRUPTED(th->ec)) {
355 /* interrupted. return immediate */
356 }
357 else {
358 RUBY_DEBUG_LOG("start msec:%lu", msec);
359 ret = w32_wait_events(0, 0, msec, th);
360 RUBY_DEBUG_LOG("done ret:%lu", ret);
361 (void)ret;
362 }
363
364 rb_native_mutex_lock(&th->interrupt_lock);
365 th->unblock.func = 0;
366 th->unblock.arg = 0;
367 rb_native_mutex_unlock(&th->interrupt_lock);
368 }
369 THREAD_BLOCKING_END(th);
370}
371
372void
373rb_native_mutex_lock(rb_nativethread_lock_t *lock)
374{
375#ifdef USE_WIN32_MUTEX
376 w32_mutex_lock(lock->mutex, false);
377#else
378 EnterCriticalSection(&lock->crit);
379#endif
380}
381
382int
383rb_native_mutex_trylock(rb_nativethread_lock_t *lock)
384{
385#ifdef USE_WIN32_MUTEX
386 return w32_mutex_lock(lock->mutex, true);
387#else
388 return TryEnterCriticalSection(&lock->crit) == 0 ? EBUSY : 0;
389#endif
390}
391
392void
393rb_native_mutex_unlock(rb_nativethread_lock_t *lock)
394{
395#ifdef USE_WIN32_MUTEX
396 RUBY_DEBUG_LOG("lock:%p", lock->mutex);
397 ReleaseMutex(lock->mutex);
398#else
399 LeaveCriticalSection(&lock->crit);
400#endif
401}
402
403void
404rb_native_mutex_initialize(rb_nativethread_lock_t *lock)
405{
406#ifdef USE_WIN32_MUTEX
407 lock->mutex = w32_mutex_create();
408 /* thread_debug("initialize mutex: %p\n", lock->mutex); */
409#else
410 InitializeCriticalSection(&lock->crit);
411#endif
412}
413
414void
415rb_native_mutex_destroy(rb_nativethread_lock_t *lock)
416{
417#ifdef USE_WIN32_MUTEX
418 w32_close_handle(lock->mutex);
419#else
420 DeleteCriticalSection(&lock->crit);
421#endif
422}
423
424struct cond_event_entry {
425 struct cond_event_entry* next;
426 struct cond_event_entry* prev;
427 HANDLE event;
428};
429
430void
431rb_native_cond_signal(rb_nativethread_cond_t *cond)
432{
433 /* cond is guarded by mutex */
434 struct cond_event_entry *e = cond->next;
435 struct cond_event_entry *head = (struct cond_event_entry*)cond;
436
437 if (e != head) {
438 struct cond_event_entry *next = e->next;
439 struct cond_event_entry *prev = e->prev;
440
441 prev->next = next;
442 next->prev = prev;
443 e->next = e->prev = e;
444
445 SetEvent(e->event);
446 }
447}
448
449void
450rb_native_cond_broadcast(rb_nativethread_cond_t *cond)
451{
452 /* cond is guarded by mutex */
453 struct cond_event_entry *e = cond->next;
454 struct cond_event_entry *head = (struct cond_event_entry*)cond;
455
456 while (e != head) {
457 struct cond_event_entry *next = e->next;
458 struct cond_event_entry *prev = e->prev;
459
460 SetEvent(e->event);
461
462 prev->next = next;
463 next->prev = prev;
464 e->next = e->prev = e;
465
466 e = next;
467 }
468}
469
470static int
471native_cond_timedwait_ms(rb_nativethread_cond_t *cond, rb_nativethread_lock_t *mutex, unsigned long msec)
472{
473 DWORD r;
474 struct cond_event_entry entry;
475 struct cond_event_entry *head = (struct cond_event_entry*)cond;
476
477 entry.event = CreateEvent(0, FALSE, FALSE, 0);
478
479 /* cond is guarded by mutex */
480 entry.next = head;
481 entry.prev = head->prev;
482 head->prev->next = &entry;
483 head->prev = &entry;
484
486 {
487 r = WaitForSingleObject(entry.event, msec);
488 if ((r != WAIT_OBJECT_0) && (r != WAIT_TIMEOUT)) {
489 rb_bug("rb_native_cond_wait: WaitForSingleObject returns %lu", r);
490 }
491 }
493
494 entry.prev->next = entry.next;
495 entry.next->prev = entry.prev;
496
497 w32_close_handle(entry.event);
498 return (r == WAIT_OBJECT_0) ? 0 : ETIMEDOUT;
499}
500
501void
502rb_native_cond_wait(rb_nativethread_cond_t *cond, rb_nativethread_lock_t *mutex)
503{
504 native_cond_timedwait_ms(cond, mutex, INFINITE);
505}
506
507static unsigned long
508abs_timespec_to_timeout_ms(const struct timespec *ts)
509{
510 struct timeval tv;
511 struct timeval now;
512
513 gettimeofday(&now, NULL);
514 tv.tv_sec = ts->tv_sec;
515 tv.tv_usec = ts->tv_nsec / 1000;
516
517 if (!rb_w32_time_subtract(&tv, &now))
518 return 0;
519
520 return (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
521}
522
523static int
524native_cond_timedwait(rb_nativethread_cond_t *cond, rb_nativethread_lock_t *mutex, const struct timespec *ts)
525{
526 unsigned long timeout_ms;
527
528 timeout_ms = abs_timespec_to_timeout_ms(ts);
529 if (!timeout_ms)
530 return ETIMEDOUT;
531
532 return native_cond_timedwait_ms(cond, mutex, timeout_ms);
533}
534
535static struct timespec native_cond_timeout(rb_nativethread_cond_t *cond, struct timespec timeout_rel);
536
537void
538rb_native_cond_timedwait(rb_nativethread_cond_t *cond, rb_nativethread_lock_t *mutex, unsigned long msec)
539{
540 struct timespec rel = {
541 .tv_sec = msec / 1000,
542 .tv_nsec = (msec % 1000) * 1000 * 1000,
543 };
544 struct timespec ts = native_cond_timeout(cond, rel);
545 native_cond_timedwait(cond, mutex, &ts);
546}
547
548static struct timespec
549native_cond_timeout(rb_nativethread_cond_t *cond, struct timespec timeout_rel)
550{
551 int ret;
552 struct timeval tv;
553 struct timespec timeout;
554 struct timespec now;
555
556 ret = gettimeofday(&tv, 0);
557 if (ret != 0)
558 rb_sys_fail(0);
559 now.tv_sec = tv.tv_sec;
560 now.tv_nsec = tv.tv_usec * 1000;
561
562 timeout.tv_sec = now.tv_sec;
563 timeout.tv_nsec = now.tv_nsec;
564 timeout.tv_sec += timeout_rel.tv_sec;
565 timeout.tv_nsec += timeout_rel.tv_nsec;
566
567 if (timeout.tv_nsec >= 1000*1000*1000) {
568 timeout.tv_sec++;
569 timeout.tv_nsec -= 1000*1000*1000;
570 }
571
572 if (timeout.tv_sec < now.tv_sec)
573 timeout.tv_sec = TIMET_MAX;
574
575 return timeout;
576}
577
578void
579rb_native_cond_initialize(rb_nativethread_cond_t *cond)
580{
581 cond->next = (struct cond_event_entry *)cond;
582 cond->prev = (struct cond_event_entry *)cond;
583}
584
585void
586rb_native_cond_destroy(rb_nativethread_cond_t *cond)
587{
588 /* */
589}
590
591
592#if !defined(_WIN32_WINNT_WIN8) || _WIN32_WINNT < 0x602
593/* declared in processthreadsapi.h only when _WIN32_WINNT >= 0x0602,
594 * but exported from kernel32.dll since Windows 8 */
595WINBASEAPI VOID WINAPI GetCurrentThreadStackLimits(PULONG_PTR, PULONG_PTR);
596#endif
597
598static void
599native_thread_init_stack(rb_thread_t *th, void *local_in_parent_frame)
600{
601 ULONG_PTR low, high;
602 SIZE_T size, space;
603
604 /* VirtualQuery against the current stack pointer may return a region
605 * that does not span the whole stack when the interpreter is
606 * initialized deep in the stack, which makes stack_check() misfire.
607 * [Bug #11438] */
608 GetCurrentThreadStackLimits(&low, &high);
609 size = high - low;
610 space = size / 5;
611 if (space > 1024*1024) space = 1024*1024;
612 th->ec->machine.stack_start = (VALUE *)high - 1;
613 th->ec->machine.stack_maxsize = size - space;
614}
615
616static void
617native_thread_destroy_atfork(struct rb_native_thread *nt)
618{
619 /* no-op */
620}
621
622#ifndef InterlockedExchangePointer
623#define InterlockedExchangePointer(t, v) \
624 (void *)InterlockedExchange((long *)(t), (long)(v))
625#endif
626static void
627native_thread_destroy(struct rb_native_thread *nt)
628{
629 if (nt) {
630 HANDLE intr = InterlockedExchangePointer(&nt->interrupt_event, 0);
631 RUBY_DEBUG_LOG("close handle intr:%p, thid:%p\n", intr, nt->thread_id);
632 w32_close_handle(intr);
633 }
634}
635
636static unsigned long __stdcall
637thread_start_func_1(void *th_ptr)
638{
639 rb_thread_t *th = th_ptr;
640 volatile HANDLE thread_id = th->nt->thread_id;
641
642 native_thread_init_stack(th, &th);
643 th->nt->interrupt_event = CreateEvent(0, TRUE, FALSE, 0);
644
645 /* run */
646 RUBY_DEBUG_LOG("thread created th:%u, thid: %p, event: %p",
647 rb_th_serial(th), th->nt->thread_id, th->nt->interrupt_event);
648
649 thread_sched_to_running(TH_SCHED(th), th);
650 ruby_thread_set_native(th);
651
652 // kick threads
653 thread_start_func_2(th, th->ec->machine.stack_start);
654
655 w32_close_handle(thread_id);
656 RUBY_DEBUG_LOG("thread deleted th:%u", rb_th_serial(th));
657
658 return 0;
659}
660
661static int
662native_thread_create(rb_thread_t *th)
663{
664 // setup nt
665 const size_t stack_size = th->vm->default_params.thread_machine_stack_size;
666 th->nt = ZALLOC(struct rb_native_thread);
667 th->nt->thread_id = w32_create_thread(stack_size, thread_start_func_1, th);
668
669 // setup vm stack
670 size_t vm_stack_word_size = th->vm->default_params.thread_vm_stack_size / sizeof(VALUE);
671 void *vm_stack = ruby_xmalloc(vm_stack_word_size * sizeof(VALUE));
672 th->sched.vm_stack = vm_stack;
673 rb_ec_initialize_vm_stack(th->ec, vm_stack, vm_stack_word_size);
674
675 if ((th->nt->thread_id) == 0) {
676 return thread_errno;
677 }
678
679 w32_resume_thread(th->nt->thread_id);
680
681 if (USE_RUBY_DEBUG_LOG) {
682 Sleep(0);
683 RUBY_DEBUG_LOG("th:%u thid:%p intr:%p), stack size: %"PRIuSIZE"",
684 rb_th_serial(th), th->nt->thread_id,
685 th->nt->interrupt_event, stack_size);
686 }
687 return 0;
688}
689
690static void
691native_thread_join(HANDLE th)
692{
693 w32_wait_events(&th, 1, INFINITE, 0);
694}
695
696#if USE_NATIVE_THREAD_PRIORITY
697
698static void
699native_thread_apply_priority(rb_thread_t *th)
700{
701 int priority = th->priority;
702 if (th->priority > 0) {
703 priority = THREAD_PRIORITY_ABOVE_NORMAL;
704 }
705 else if (th->priority < 0) {
706 priority = THREAD_PRIORITY_BELOW_NORMAL;
707 }
708 else {
709 priority = THREAD_PRIORITY_NORMAL;
710 }
711
712 SetThreadPriority(th->nt->thread_id, priority);
713}
714
715#endif /* USE_NATIVE_THREAD_PRIORITY */
716
717int rb_w32_select_with_thread(int, fd_set *, fd_set *, fd_set *, struct timeval *, void *); /* @internal */
718
719static int
720native_fd_select(int n, rb_fdset_t *readfds, rb_fdset_t *writefds, rb_fdset_t *exceptfds, struct timeval *timeout, rb_thread_t *th)
721{
722 fd_set *r = NULL, *w = NULL, *e = NULL;
723 if (readfds) {
724 rb_fd_resize(n - 1, readfds);
725 r = rb_fd_ptr(readfds);
726 }
727 if (writefds) {
728 rb_fd_resize(n - 1, writefds);
729 w = rb_fd_ptr(writefds);
730 }
731 if (exceptfds) {
732 rb_fd_resize(n - 1, exceptfds);
733 e = rb_fd_ptr(exceptfds);
734 }
735 return rb_w32_select_with_thread(n, r, w, e, timeout, th);
736}
737
738/* @internal */
739int
740rb_w32_check_interrupt(rb_thread_t *th)
741{
742 return w32_wait_events(0, 0, 0, th);
743}
744
745static void
746ubf_handle(void *ptr)
747{
748 rb_thread_t *th = (rb_thread_t *)ptr;
749 RUBY_DEBUG_LOG("th:%u\n", rb_th_serial(th));
750
751 if (!SetEvent(th->nt->interrupt_event)) {
752 w32_error("ubf_handle");
753 }
754}
755
756int rb_w32_set_thread_description(HANDLE th, const WCHAR *name);
757int rb_w32_set_thread_description_str(HANDLE th, VALUE name);
758#define native_set_another_thread_name rb_w32_set_thread_description_str
759
760static struct {
761 HANDLE id;
762 HANDLE lock;
763} timer_thread;
764#define TIMER_THREAD_CREATED_P() (timer_thread.id != 0)
765
766static unsigned long __stdcall
767timer_thread_func(void *dummy)
768{
769 rb_vm_t *vm = GET_VM();
770 RUBY_DEBUG_LOG("start");
771 rb_w32_set_thread_description(GetCurrentThread(), L"ruby-timer-thread");
772 while (WaitForSingleObject(timer_thread.lock,
773 TIME_QUANTUM_USEC/1000) == WAIT_TIMEOUT) {
774 vm->clock++;
775 rb_threadptr_check_signal(vm->ractor.main_thread);
776 }
777 RUBY_DEBUG_LOG("end");
778 return 0;
779}
780
781void
782rb_thread_wakeup_timer_thread(int sig)
783{
784 /* do nothing */
785}
786
787static void
788rb_thread_create_timer_thread(void)
789{
790 if (timer_thread.id == 0) {
791 if (!timer_thread.lock) {
792 timer_thread.lock = CreateEvent(0, TRUE, FALSE, 0);
793 }
794 timer_thread.id = w32_create_thread(1024 + (USE_RUBY_DEBUG_LOG ? BUFSIZ : 0),
795 timer_thread_func, 0);
796 w32_resume_thread(timer_thread.id);
797 }
798}
799
800static int
801native_stop_timer_thread(void)
802{
803 RUBY_ATOMIC_SET(system_working, 0);
804
805 SetEvent(timer_thread.lock);
806 native_thread_join(timer_thread.id);
807 CloseHandle(timer_thread.lock);
808 timer_thread.lock = 0;
809
810 return 1;
811}
812
813static void
814native_reset_timer_thread(void)
815{
816 if (timer_thread.id) {
817 CloseHandle(timer_thread.id);
818 timer_thread.id = 0;
819 }
820}
821
822int
823ruby_stack_overflowed_p(const rb_thread_t *th, const void *addr)
824{
825 return rb_ec_raised_p(th->ec, RAISED_STACKOVERFLOW);
826}
827
828#if defined(__MINGW32__)
829LONG WINAPI
830rb_w32_stack_overflow_handler(struct _EXCEPTION_POINTERS *exception)
831{
832 if (exception->ExceptionRecord->ExceptionCode == EXCEPTION_STACK_OVERFLOW) {
833 rb_ec_raised_set(GET_EC(), RAISED_STACKOVERFLOW);
834 raise(SIGSEGV);
835 }
836 return EXCEPTION_CONTINUE_SEARCH;
837}
838#endif
839
840#ifdef RUBY_ALLOCA_CHKSTK
841void
842ruby_alloca_chkstk(size_t len, void *sp)
843{
844 if (ruby_stack_length(NULL) * sizeof(VALUE) >= len) {
845 rb_execution_context_t *ec = GET_EC();
846 if (!rb_ec_raised_p(ec, RAISED_STACKOVERFLOW)) {
847 rb_ec_raised_set(ec, RAISED_STACKOVERFLOW);
848 rb_exc_raise(sysstack_error);
849 }
850 }
851}
852#endif
853int
854rb_reserved_fd_p(int fd)
855{
856 return 0;
857}
858
859rb_nativethread_id_t
861{
862 return GetCurrentThread();
863}
864
865static void
866native_set_thread_name(rb_thread_t *th)
867{
868}
869
870static VALUE
871native_thread_native_thread_id(rb_thread_t *th)
872{
873 DWORD tid = GetThreadId(th->nt->thread_id);
874 if (tid == 0) rb_sys_fail("GetThreadId");
875 return ULONG2NUM(tid);
876}
877#define USE_NATIVE_THREAD_NATIVE_THREAD_ID 1
878
879void
880rb_add_running_thread(rb_thread_t *th)
881{
882 // do nothing
883}
884
885void
886rb_del_running_thread(rb_thread_t *th)
887{
888 // do nothing
889}
890
891static bool
892th_has_dedicated_nt(const rb_thread_t *th)
893{
894 return true;
895}
896
897void
898rb_threadptr_sched_free(rb_thread_t *th)
899{
900 native_thread_destroy(th->nt);
901 ruby_xfree(th->nt);
902 ruby_xfree(th->sched.vm_stack);
903}
904
905void
906rb_threadptr_remove(rb_thread_t *th)
907{
908 // do nothing
909}
910
911void
912rb_thread_sched_mark_zombies(rb_vm_t *vm)
913{
914 // do nothing
915}
916
917static bool
918vm_barrier_finish_p(rb_vm_t *vm)
919{
920 RUBY_DEBUG_LOG("cnt:%u living:%u blocking:%u",
921 vm->ractor.blocking_cnt == vm->ractor.cnt,
922 vm->ractor.sync.barrier_cnt,
923 vm->ractor.cnt,
924 vm->ractor.blocking_cnt);
925
926 VM_ASSERT(vm->ractor.blocking_cnt <= vm->ractor.cnt);
927
928 return vm->ractor.blocking_cnt == vm->ractor.cnt;
929}
930
931void
932rb_ractor_sched_barrier_start(rb_vm_t *vm, rb_ractor_t *cr)
933{
934 vm->ractor.sync.barrier_waiting = true;
935
936 RUBY_DEBUG_LOG("barrier start. cnt:%u living:%u blocking:%u",
937 vm->ractor.sync.barrier_cnt,
938 vm->ractor.cnt,
939 vm->ractor.blocking_cnt);
940
941 rb_vm_ractor_blocking_cnt_inc(vm, cr, __FILE__, __LINE__);
942
943 // send signal
944 rb_ractor_t *r = 0;
945 ccan_list_for_each(&vm->ractor.set, r, vmlr_node) {
946 if (r != cr) {
947 rb_ractor_vm_barrier_interrupt_running_thread(r);
948 }
949 }
950
951 // wait
952 while (!vm_barrier_finish_p(vm)) {
953 rb_vm_cond_wait(vm, &vm->ractor.sync.barrier_complete_cond);
954 }
955
956 RUBY_DEBUG_LOG("cnt:%u barrier success", vm->ractor.sync.barrier_cnt);
957
958 rb_vm_ractor_blocking_cnt_dec(vm, cr, __FILE__, __LINE__);
959
960 vm->ractor.sync.barrier_waiting = false;
961 vm->ractor.sync.barrier_cnt++;
962
963 rb_native_cond_broadcast(&vm->ractor.sync.barrier_release_cond);
964}
965
966void
967rb_ractor_sched_barrier_join(rb_vm_t *vm, rb_ractor_t *cr)
968{
969 vm->ractor.sync.lock_owner = cr;
970 unsigned int barrier_cnt = vm->ractor.sync.barrier_cnt;
971 rb_thread_t *th = GET_THREAD();
972 bool running;
973
974 RB_VM_SAVE_MACHINE_CONTEXT(th);
975
976 if (rb_ractor_status_p(cr, ractor_running)) {
977 rb_vm_ractor_blocking_cnt_inc(vm, cr, __FILE__, __LINE__);
978 running = true;
979 }
980 else {
981 running = false;
982 }
983 VM_ASSERT(rb_ractor_status_p(cr, ractor_blocking));
984
985 if (vm_barrier_finish_p(vm)) {
986 RUBY_DEBUG_LOG("wakeup barrier owner");
987 rb_native_cond_signal(&vm->ractor.sync.barrier_complete_cond);
988 }
989 else {
990 RUBY_DEBUG_LOG("wait for barrier finish");
991 }
992
993 // wait for restart
994 while (barrier_cnt == vm->ractor.sync.barrier_cnt) {
995 rb_vm_cond_wait(vm, &vm->ractor.sync.barrier_release_cond);
996 }
997
998 RUBY_DEBUG_LOG("barrier is released. Acquire vm_lock");
999
1000 if (running) {
1001 rb_vm_ractor_blocking_cnt_dec(vm, cr, __FILE__, __LINE__);
1002 }
1003
1004 vm->ractor.sync.lock_owner = NULL;
1005}
1006
1007bool
1009{
1010 return false;
1011}
1012
1013void *
1014rb_thread_prevent_fork(void *(*func)(void *), void *data)
1015{
1016 return func(data);
1017}
1018
1019void
1020rb_thread_malloc_stack_set(rb_thread_t *th, void *stack)
1021{
1022 // no-op
1023}
1024
1025#endif /* THREAD_SYSTEM_DEPENDENT_IMPLEMENTATION */
#define RUBY_ATOMIC_SET(var, val)
Identical to RUBY_ATOMIC_EXCHANGE, except for the return type.
Definition atomic.h:185
uint32_t rb_event_flag_t
Represents event(s).
Definition event.h:108
#define UNREACHABLE
Old name of RBIMPL_UNREACHABLE.
Definition assume.h:28
#define ULONG2NUM
Old name of RB_ULONG2NUM.
Definition long.h:60
#define ZALLOC
Old name of RB_ZALLOC.
Definition memory.h:402
size_t ruby_stack_length(VALUE **p)
Queries what Ruby thinks is the machine stack.
Definition gc.c:2550
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition eval.c:664
int rb_reserved_fd_p(int fd)
Queries if the given FD is reserved or not.
char * ptr
Pointer to the underlying memory region, of at least capa bytes.
Definition io.h:2
int len
Length of the buffer.
Definition io.h:8
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_thread_lock_native_thread(void)
Declare the current Ruby thread should acquire a dedicated native thread on M:N thread scheduler.
bool rb_internal_thread_remove_event_hook(rb_internal_thread_event_hook_t *hook)
Unregister the passed hook.
#define ALLOCA_N(type, n)
Definition memory.h:292
#define RBIMPL_ATTR_NORETURN()
Wraps (or simulates) [[noreturn]].
Definition noreturn.h:38
#define errno
Ractor-aware version of errno.
Definition ruby.h:388
#define rb_fd_resize(n, f)
Does nothing (defined for compatibility).
Definition select.h:43
The data structure which wraps the fd_set bitmap used by select(2).
Definition largesize.h:71
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.
Definition value.h:40
void ruby_xfree(void *ptr)
Deallocates a storage instance.
Definition gc.c:5279