Skip to content

Commit

Permalink
Protect constant initializers with mutex on Windows (#15134)
Browse files Browse the repository at this point in the history
`Crystal::System::FileDescriptor#@@reader_thread` is initialized before `Crystal::System::Fiber::RESERVED_STACK_SIZE` which creates a race condition.
Regression from #14947
  • Loading branch information
HertzDevil authored Oct 31, 2024
1 parent 8635bce commit 4aac6f2
Showing 1 changed file with 7 additions and 4 deletions.
11 changes: 7 additions & 4 deletions src/crystal/once.cr
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,6 @@
# :nodoc:
class Crystal::OnceState
@rec = [] of Bool*
{% if flag?(:preview_mt) %}
@mutex = Mutex.new(:reentrant)
{% end %}

def once(flag : Bool*, initializer : Void*)
unless flag.value
Expand All @@ -29,7 +26,13 @@ class Crystal::OnceState
end
end

{% if flag?(:preview_mt) %}
# on Win32, `Crystal::System::FileDescriptor#@@reader_thread` spawns a new
# thread even without the `preview_mt` flag, and the thread can also reference
# Crystal constants, leading to race conditions, so we always enable the mutex
# TODO: can this be improved?
{% if flag?(:preview_mt) || flag?(:win32) %}
@mutex = Mutex.new(:reentrant)

def once(flag : Bool*, initializer : Void*)
unless flag.value
@mutex.synchronize do
Expand Down

0 comments on commit 4aac6f2

Please sign in to comment.