Created
September 30, 2019 20:01
-
-
Save bcardiff/d6d0cc7d9b58aa68a2fa892a9a1765a6 to your computer and use it in GitHub Desktop.
Synchronized shameless wrapped for Crystal
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
# $ crystal run -Dpreview_mt synchronized.cr | |
struct Synchronized(T) | |
@lock = Mutex.new | |
getter inner : T | |
def initialize(@inner : T) | |
end | |
macro method_missing(call) | |
@lock.synchronize do | |
@inner.{{call}} | |
end | |
end | |
end | |
ary = Array(Int32).new | |
ary = Synchronized.new(ary) | |
ch = Channel(Nil).new | |
8.times do | |
spawn do | |
1000.times do |n| | |
ary << n | |
end | |
ch.send nil | |
end | |
end | |
8.times do | |
ch.receive | |
end | |
puts ary.size |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment