From: 7stud -- Date: 2007-09-20T13:19:30+09:00 Subject: thread switching? (p. 144 pickaxe2) Hi, On p. 144 in pickaxe2, there are two examples using threads(see below). Each thread updates a counter, and the function call that updates the counter is synchronized to prevent simultaneous axis to the counter. Presumably, one thread doesn't update the counter 100,000 times, followed by the other thread updating the counter 100,000 times--that wouldn't execute anything simultaneously, which is the whole point of threads. Therefore, it seems reasonable to assume that execution switches between the threads. In fact, there is a table on p. 143 that illustrates what happens when thread switching occurs in the unsynchronized case. But on p. 145, there is an example that creates two threads: a producer thread and a consumer thread. The consumer thread is regularly put to sleep while it awaits data from the producer thread, which I assume would cause execution to switch to the producer thread. However, the text explains cryptically, "But because *we* own the monitor, the [producer thread] will never be able to enter its synchronization block, and will never add something to the playlist." First of all, as far as I can tell, I'm the only one in the room reading the book; there is no "we'. Second of all, I have never and will never own a monitor object. What kind of description is that? Is pickaxe2 a children's book about bears eating porridge or something? Maybe in future versions the author could use a more professional writing style? In any case, why doesn't thread switching happen in the example on p. 145: playlist = [] playlist.extend(MonitorMixin) #Player thread Thread.new do record = nil loop do puts "*" playlist.synchronize do sleep 0.1 while playlist.empty? record = playlist.shift end puts record end end #Customer request thread Thread.new do loop do puts "-" playlist.synchronize do playlist << "hello" end end end and why is the output: * - ...yet thread switching does occur in the example on p. 144: 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 do 100_000.times do lock.synchronize do c.tick end end end t2 = Thread.new do 100_000.times do lock.synchronize do c.tick end end end t1.join t2.join puts c.count -- Posted via http://www.ruby-forum.com/.