Skip to content

Instantly share code, notes, and snippets.

@alanhala
Created April 11, 2018 19:18
Show Gist options
  • Save alanhala/a627a440de95e13459a6d07ed22b6417 to your computer and use it in GitHub Desktop.
Save alanhala/a627a440de95e13459a6d07ed22b6417 to your computer and use it in GitHub Desktop.
MRI-GIL Context switch examples from this talk: https://www.youtube.com/watch?v=1nNfTWHF2YY
@bank_account = 0
# WORKS
# 100.times.map do
# Thread.new do
# 10_000.times do
# value = @bank_account
# value = value + 1
# @bank_account = value
# end
# end
# end.each(&:join)
##################################################################################################
# RACE CONDITION BECAUSE MRI MAKES A CONTEXT SWITCH WHEN CALLING A METHOD
# def read_from_bank_account
# @bank_account
# end
# def write_bank_account(value)
# @bank_account = value
# end
# 100.times.map do
# Thread.new do
# 10_000.times do
# value = read_from_bank_account
# value = value + 1
# write_bank_account(value)
# end
# end
# end.each(&:join)
##################################################################################################
# WORKS
# 100.times.map do
# Thread.new do
# 10_000.times do
# value = @bank_account
# value = value + 1 if true
# @bank_account = value
# end
# end
# end.each(&:join)
##################################################################################################
# RACE CONDITION USING RUBY 2.3.1. YOU MAY NEED TO RUN THIS SCRIPT SEVERAL TIME UNTIL YOU GET AN ERROR
# THIS WORKS ON RUBY 2.4 BECAUSE OF AN OPTIMIZATION OF UNREACHABLE CODE
# CHANGING THE UNLESS WITH: some_variable = false; unless some_variable && false THE RACE CONDITION APPEARS AGAIN
# 100.times.map do
# Thread.new do
# 10_000.times do
# value = @bank_account
# value = value + 1 unless false
# @bank_account = value
# end
# end
# end.each(&:join)
print @bank_account
puts @bank_account == 1_000_000 ? "\e[32m CORRECT \e[0m" : "\e[31m ERROR \e[0m"
@DanielVartanov
Copy link

Hey
Thanks for taking interest in my talk, I accidentally came across this gist. Just in case here is the full script&codes of the talk: https://github.com/DanielVartanov/rubyconf-2017-talk-what-does-gil-really-guarantee-you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment