Last active
June 19, 2024 11:17
-
-
Save ysbaddaden/96b1367123464329e814d5cb91bb031e to your computer and use it in GitHub Desktop.
stw.cr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class STW | |
def initialize | |
@running = true | |
@started = Atomic(Int32).new(0) | |
@count = Atomic(Int32).new(0) | |
@threads = [] of Thread | |
end | |
def start_thread | |
@threads << Thread.new do | |
Crystal::System.print_error "starting thread: %p\n", Thread.current.as(Void*) | |
@started.add(1) | |
while @running | |
@count.add(1) | |
end | |
Crystal::System.print_error "exiting thread: %p count=%d\n", Thread.current.as(Void*), @count.get | |
@started.sub(1) | |
end | |
end | |
def join | |
@running = false | |
@threads.map(&.join) | |
end | |
end | |
stw = STW.new | |
Crystal::System.print_error "starting threads...\n" | |
4.times { stw.start_thread } | |
until [email protected] == 4 | |
Thread.yield | |
end | |
Crystal::System.print_error "WORLD IS RUNNING!\n" | |
Crystal::System.print_error "suspending threads...\n" | |
Thread.stop_world | |
Crystal::System.print_error "WORLD IS STOPPED!\n" | |
5.times do | |
Crystal::System.print_error "count = %d (it musn't change)\n", [email protected] | |
Thread.sleep(1.second) | |
end | |
# debugger | |
Crystal::System.print_error "resuming threads...\n" | |
Thread.start_world | |
Crystal::System.print_error "WORLD IS RUNNING AGAIN!\n" | |
Crystal::System.print_error "stopping threads...\n" | |
stw.join | |
until [email protected] == 0 | |
Thread.yield | |
end | |
Crystal::System.print_error "WORLD IS DONE!\n" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment