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