2007年 04月 05日

非同期を同期っぽくする方法

callcc
コールバックからもとの継続を呼ぶ (一度メソッドから抜ける)

# 同時にいくつも呼ぶことを想定していない
	def hoge(sender)
		@foo.set_callback(self, :event_callback)
		@foo.load_something 
		if callcc { |@c| false }
			p "loaded"
			@c = nil
		end
	end

	def event_callback
		@c.call(true) if @c
	end

Queue
Queue#pop のブロッキングを使う

# 同時にいくつも呼ぶことを想定していない
	def hoge(sender)
		@q ||= Queue.new
		@foo.set_callback(self, :event_callback)
		@foo.load_something 
		@q.pop
		p "loaded"
	end

	def event_callback
		@q << :callback
	end

なんかもっと簡単なのがあるのかなぁ