From: Morton Goldberg Date: 2007-09-20T19:23:52+09:00 Subject: Re: thread switching? (p. 144 pickaxe2) On Sep 20, 2007, at 12:19 AM, 7stud -- wrote: > 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. Since you are picky enough to complain about the writing in Pickaxe 2, I feel justified in pointing out that your "axis" should be "access". > In any case, why doesn't thread switching happen in the example on p. > 145: There are two problems with this code. > playlist = [] > playlist.extend(MonitorMixin) > > #Player thread > Thread.new do > record = nil > loop do > puts "*" > playlist.synchronize do 1. The "while playlist.empty?" causes deadlock. > 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 2. The main thread exits immediately killing both child threads. The following will run for 2 seconds before dying. #! /usr/bin/env ruby -w require "monitor" playlist = [] playlist.extend(MonitorMixin) pending = playlist.new_cond Thread.abort_on_exception = true Thread.new do record = 'none' loop do puts "*" playlist.synchronize do pending.wait_while { playlist.empty? } record = playlist.shift end p record end end Thread.new do loop do puts "-" playlist.synchronize do sleep 0.5 playlist << "hello" pending.signal end p playlist end end sleep 2 Regards, Morton