-
Notifications
You must be signed in to change notification settings - Fork 4
/
002_eq_or_race.rb
55 lines (42 loc) · 1.03 KB
/
002_eq_or_race.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
require 'thread' # to use Queue
class FileUploader
def initialize(files)
@files = files
end
def upload
threads = []
@files.each do |(filename, file_data)|
threads << Thread.new do
status = upload_to_s3(filename, file_data)
results << status
end
end
threads.each(&:join)
end
def results
# Threads share AST, so here might be a race condition (one thread creates Queue,
# then another one creates it again)
# To fix: move assignment to #initialize
@results ||= Queue.new
end
def upload_to_s3(filename, file_data)
# immitate upload
sleep 0.1
puts "Uploaded #{filename} to S3"
"success"
end
end
# ------ main ------
files = {
'boots.png' => '*image data*',
'shirts.png' => '*image data*'
}
expected_count = 2
100.times do
uploader = FileUploader.new(files)
uploader.upload
actual_size = uploader.results.size
fail("Race condition, size = #{actual_size}") if actual_size != expected_count
end
puts "No race condition this time"
exit(0)