Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- gem 'thread' # gem install thread
- require 'thread/pool'
- @semaphore = Mutex.new
- LOOPS_COUNT = (ENV['LOOPS_COUNT'] || 100).to_i
- POOL_SIZE = (ENV['POOL_SIZE'] || LOOPS_COUNT).to_i
- def with_thread_without_mutex!(num_loops = 100)
- executions = num_loops.times.map do |i|
- Thread.new do
- count = (File.read('test.txt') || 0).to_i
- File.open('test.txt', 'wb') do |file|
- file.write((count + 1).to_s)
- end
- end
- end
- executions.map(&:join)
- end
- def with_thread_mutex!(num_loops = 100)
- executions = num_loops.times.map do |i|
- Thread.new do
- @semaphore.synchronize do
- count = (File.read('test.txt') || 0).to_i
- File.open('test.txt', 'wb') do |file|
- # puts "Current count = #{count} | Next count = #{count + 1}"
- file.write((count + 1).to_s)
- end
- end
- end
- end
- executions.map(&:join)
- end
- def with_thread_pool!(pool_size = 100, num_loops = 100)
- pool = Thread.pool(num_loops)
- num_loops.times do |i|
- pool.process do
- @semaphore.synchronize do
- count = (File.read('test.txt') || 0).to_i
- File.open('test.txt', 'wb') do |file|
- # puts "Current count = #{count} | Next count = #{count + 1}"
- file.write((count + 1).to_s)
- end
- end
- end
- end
- pool.shutdown
- end
- def without_thread!(num_loops = 100)
- num_loops.times do |i|
- count = (File.read('test.txt') || 0).to_i
- File.open('test.txt', 'wb') do |file|
- file.write((count + 1).to_s)
- end
- end
- end
- def test!(label, value)
- if File.read('test.txt').to_i != value
- puts "Error for \"#{label}\". The file 'test.txt' must have the exact value 200"
- end
- end
- def truncate!
- File.truncate('test.txt', 0)
- end
- def with_time(label, &block)
- start_time = Time.now
- yield block if block_given?
- end_time = Time.now
- puts "Total time for \"#{label}\" ==> #{((end_time - start_time) * 100).round(2)} ms"
- end
- with_time("with_thread_pool!") do
- truncate!
- with_thread_pool!(POOL_SIZE, LOOPS_COUNT)
- test!("with_thread_pool!", LOOPS_COUNT)
- end
- sleep(2)
- with_time("with_thread_mutex!") do
- truncate!
- with_thread_mutex!(LOOPS_COUNT)
- test!("with_thread_mutex!", LOOPS_COUNT)
- end
- sleep(2)
- with_time("without_thread!") do
- truncate!
- without_thread!(LOOPS_COUNT)
- test!("without_thread!", LOOPS_COUNT)
- end
Add Comment
Please, Sign In to add comment