Skip to content

Commit 5add7c3

Browse files
authored
Fix RUBY_MN_THREADS sleep returning prematurely (ruby#15868)
timer_thread_check_exceed() was returning true when the remaining time was less than 1ms, treating it as "too short time". This caused sub-millisecond sleeps (like sleep(0.0001)) to return immediately instead of actually sleeping. The fix removes this optimization that was incorrectly short-circuiting short sleep durations. Now the timeout is only considered exceeded when the actual deadline has passed. Note: There's still a separate performance issue where MN_THREADS mode is slower for sub-millisecond sleeps due to the timer thread using millisecond-resolution polling. This will require a separate fix to use sub-millisecond timeouts in kqueue/epoll. [Bug #21836]
1 parent 2947aa4 commit 5add7c3

File tree

2 files changed

+13
-9
lines changed

2 files changed

+13
-9
lines changed

test/ruby/test_thread.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1652,4 +1652,16 @@ def test_mutexes_locked_in_fiber_dont_have_aba_issue_with_new_fibers
16521652
end
16531653
end;
16541654
end
1655+
1656+
# [Bug #21836]
1657+
def test_mn_threads_sub_millisecond_sleep
1658+
assert_separately([{'RUBY_MN_THREADS' => '1'}], "#{<<~"begin;"}\n#{<<~'end;'}", timeout: 30)
1659+
begin;
1660+
t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
1661+
1000.times { sleep 0.0001 }
1662+
t1 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
1663+
elapsed = t1 - t0
1664+
assert_operator elapsed, :>=, 0.1, "sub-millisecond sleeps should not return immediately"
1665+
end;
1666+
end
16551667
end

thread_pthread.c

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2947,15 +2947,7 @@ timer_thread_check_signal(rb_vm_t *vm)
29472947
static bool
29482948
timer_thread_check_exceed(rb_hrtime_t abs, rb_hrtime_t now)
29492949
{
2950-
if (abs < now) {
2951-
return true;
2952-
}
2953-
else if (abs - now < RB_HRTIME_PER_MSEC) {
2954-
return true; // too short time
2955-
}
2956-
else {
2957-
return false;
2958-
}
2950+
return abs <= now;
29592951
}
29602952

29612953
static rb_thread_t *

0 commit comments

Comments
 (0)