Skip to content

Commit

Permalink
threads
Browse files Browse the repository at this point in the history
  • Loading branch information
Manvendra committed Nov 23, 2018
1 parent 86f709e commit 5029095
Show file tree
Hide file tree
Showing 5 changed files with 84 additions and 0 deletions.
25 changes: 25 additions & 0 deletions 19F/Threads.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Thread - a light weight process.
# Threads which belongs to a process shares the resources of that process.
#
# In Ruby - Thread class can be used to create thread.
t1 = Time.now
def sum(array)
sleep(2)
sum = 0
array.each do | i |
sum += i
end
sum
end

@item1 = [1,2,3,4,5]
@item2 = [6,7,8,9,10]
@item3 = [11,12,13,14,15]

puts "item1 #{sum(@item1)}"
puts "item2 #{sum(@item2)}"
puts "item3 #{sum(@item3)}"

t2 = Time.now

puts "Total time taken to complete the prg is #{t2 - t1}"
29 changes: 29 additions & 0 deletions 19F/thread3.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
class A
class << self
attr_accessor :price
end
@price = 0
end

mutex = Mutex.new

thread = (1..10).map do | i |

Thread.new(i) do | i |
mutex.synchronize do
items = A.price
sleep(rand(0..2))
items += 10
sleep(rand(0..2))
A.price = items
end
end
end


thread.each {|t| t.join}

puts A.price


Thread.abort_on_exception = true
25 changes: 25 additions & 0 deletions 19F/use_thread.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
t1 = Time.now
def sum(array)
sleep(2)
sum = 0
array.each do | i |
sum += i
end
sum
end

@item1 = [1,2,3,4,5]
@item2 = [6,7,8,9,10]
@item3 = [11,12,13,14,15]

thread = (1..3).map do | i |
Thread.new(i) do | i |
items = instance_variable_get("@item#{i}")
puts "item#{i} #{sum(items)}"
end
end
thread.each {|t| t.join}

t2 = Time.now

puts "Total time taken to complete the prg is #{t2 - t1}"
1 change: 1 addition & 0 deletions demo_app/Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ gem 'autoprefixer-rails'
gem "paperclip"
gem 'rspec'
gem 'rspec-rails'
gem 'httparty'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.1.6'
# Use sqlite3 as the database for Active Record
Expand Down
4 changes: 4 additions & 0 deletions demo_app/Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,8 @@ GEM
ffi (1.9.25)
globalid (0.4.1)
activesupport (>= 4.2.0)
httparty (0.14.0)
multi_xml (>= 0.5.2)
i18n (1.1.1)
concurrent-ruby (~> 1.0)
jbuilder (2.8.0)
Expand All @@ -106,6 +108,7 @@ GEM
mini_portile2 (2.3.0)
minitest (5.11.3)
multi_json (1.13.1)
multi_xml (0.6.0)
net-scp (1.2.1)
net-ssh (>= 2.6.5)
net-ssh (5.0.2)
Expand Down Expand Up @@ -234,6 +237,7 @@ DEPENDENCIES
capistrano
capybara (~> 2.13)
coffee-rails (~> 4.2)
httparty
jbuilder (~> 2.5)
listen (>= 3.0.5, < 3.2)
paperclip
Expand Down

0 comments on commit 5029095

Please sign in to comment.