-
Notifications
You must be signed in to change notification settings - Fork 0
/
threads_and_mutex.rb
66 lines (44 loc) · 1.28 KB
/
threads_and_mutex.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
56
57
58
59
60
61
62
63
64
65
66
require 'thread'
puts "\nUsing script"
# Shared resource
counter = 0
mutex = Mutex.new
def increment_counter(mutex, counter)
mutex.synchronize do
counter += 1
end
end
threads = []
10.times do
threads << Thread.new { counter = increment_counter(mutex, counter) }
end
threads.each(&:join)
puts "Final value of counter: #{counter}"
puts "\nUsing class"
require 'thread'
class ExampleClass
attr_accessor :counter
def initialize
@mutex = Mutex.new
@counter = 0
end
def auto_increment_id
@mutex.synchronize do
@counter += 1
puts @counter
end
end
end
obj = ExampleClass.new
threads = []
10.times do
threads << Thread.new { obj.auto_increment_id }
end
threads.each(&:join)
puts "Final counter value: #{obj.counter}"
# Lock: A general term for a synchronization mechanism used to control access to shared resources in concurrent programming.
# Mutex (Mutual Exclusion): Ensures mutual exclusion, allowing only one thread to access a shared resource at a time.
# Eg. Auto increment counter
# Semaphore: Allows a fixed number of threads to access a shared resource concurrently, within specified limits.
# Eg. Parking lot with 100 parkings. If semaphore counter is <100 then new car will be allowed, if counter >=100 then new
# car won't be allowed.