Pages 136-7: Mutual exclusion - Monitors (part II)
Listen to this article.
Value: Average
Level: Easy
Summary:
You can include MonitorMixin instead of using Monitor as a superclass. If all accesses to all objects of the class require synchronization, you'll put synchronization inside the resource being synchronized (see previous post). Otherwise you can use an external monitor.
Memo: While external monitors are safe, try to avoid making specific objects into monitors.
Example:
require 'monitor'
class Counter
attr_reader :count
def initialize
@count = 0
end
def tick
@count += 1
end
end
c = Counter.new
lock = Monitor.new
t1 = Thread.new { 10000.times { lock.synchronize { c.tick } } }
t2 = Thread.new { 10000.times { lock.synchronize { c.tick } } }
t1.join; t2.join
c.count
Reported errata (at 10/17/06 14:17:18 PDT): 0
Errata I found: 0
My suggestions to the author: 0
Doubts: 0
Level: Easy
Summary:
You can include MonitorMixin instead of using Monitor as a superclass. If all accesses to all objects of the class require synchronization, you'll put synchronization inside the resource being synchronized (see previous post). Otherwise you can use an external monitor.
Memo: While external monitors are safe, try to avoid making specific objects into monitors.
Example:
require 'monitor'
class Counter
attr_reader :count
def initialize
@count = 0
end
def tick
@count += 1
end
end
c = Counter.new
lock = Monitor.new
t1 = Thread.new { 10000.times { lock.synchronize { c.tick } } }
t2 = Thread.new { 10000.times { lock.synchronize { c.tick } } }
t1.join; t2.join
c.count
Reported errata (at 10/17/06 14:17:18 PDT): 0
Errata I found: 0
My suggestions to the author: 0
Doubts: 0
0 Comments:
Post a Comment
<< Home