Guest User

Untitled

a guest
Jan 22nd, 2019
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. gem 'thread' # gem install thread
  2.  
  3. require 'thread/pool'
  4.  
  5. @semaphore = Mutex.new
  6.  
  7. LOOPS_COUNT = (ENV['LOOPS_COUNT'] || 100).to_i
  8. POOL_SIZE = (ENV['POOL_SIZE'] || LOOPS_COUNT).to_i
  9.  
  10. def with_thread_without_mutex!(num_loops = 100)
  11. executions = num_loops.times.map do |i|
  12. Thread.new do
  13. count = (File.read('test.txt') || 0).to_i
  14.  
  15. File.open('test.txt', 'wb') do |file|
  16. file.write((count + 1).to_s)
  17. end
  18. end
  19. end
  20.  
  21. executions.map(&:join)
  22. end
  23.  
  24. def with_thread_mutex!(num_loops = 100)
  25. executions = num_loops.times.map do |i|
  26. Thread.new do
  27. @semaphore.synchronize do
  28. count = (File.read('test.txt') || 0).to_i
  29.  
  30. File.open('test.txt', 'wb') do |file|
  31. # puts "Current count = #{count} | Next count = #{count + 1}"
  32. file.write((count + 1).to_s)
  33. end
  34. end
  35. end
  36. end
  37.  
  38. executions.map(&:join)
  39. end
  40.  
  41. def with_thread_pool!(pool_size = 100, num_loops = 100)
  42. pool = Thread.pool(num_loops)
  43.  
  44. num_loops.times do |i|
  45. pool.process do
  46. @semaphore.synchronize do
  47. count = (File.read('test.txt') || 0).to_i
  48.  
  49. File.open('test.txt', 'wb') do |file|
  50. # puts "Current count = #{count} | Next count = #{count + 1}"
  51. file.write((count + 1).to_s)
  52. end
  53. end
  54. end
  55. end
  56.  
  57. pool.shutdown
  58. end
  59.  
  60.  
  61. def without_thread!(num_loops = 100)
  62. num_loops.times do |i|
  63. count = (File.read('test.txt') || 0).to_i
  64.  
  65. File.open('test.txt', 'wb') do |file|
  66. file.write((count + 1).to_s)
  67. end
  68. end
  69. end
  70.  
  71. def test!(label, value)
  72. if File.read('test.txt').to_i != value
  73. puts "Error for \"#{label}\". The file 'test.txt' must have the exact value 200"
  74. end
  75. end
  76.  
  77. def truncate!
  78. File.truncate('test.txt', 0)
  79. end
  80.  
  81. def with_time(label, &block)
  82. start_time = Time.now
  83. yield block if block_given?
  84. end_time = Time.now
  85.  
  86. puts "Total time for \"#{label}\" ==> #{((end_time - start_time) * 100).round(2)} ms"
  87. end
  88.  
  89. with_time("with_thread_pool!") do
  90. truncate!
  91. with_thread_pool!(POOL_SIZE, LOOPS_COUNT)
  92. test!("with_thread_pool!", LOOPS_COUNT)
  93. end
  94.  
  95. sleep(2)
  96.  
  97. with_time("with_thread_mutex!") do
  98. truncate!
  99. with_thread_mutex!(LOOPS_COUNT)
  100. test!("with_thread_mutex!", LOOPS_COUNT)
  101. end
  102.  
  103. sleep(2)
  104.  
  105. with_time("without_thread!") do
  106. truncate!
  107. without_thread!(LOOPS_COUNT)
  108. test!("without_thread!", LOOPS_COUNT)
  109. end
Add Comment
Please, Sign In to add comment