OSDN Git Service

Validate a yaml file for floodagte history. If it is invalid, the default value ...
[shogi-server/shogi-server.git] / shogi_server / timeout_queue.rb
1 ## $Id$
2
3 ## Copyright (C) 2004 NABEYA Kenichi (aka nanami@2ch)
4 ## Copyright (C) 2007-2008 Daigo Moriwaki (daigo at debian dot org)
5 ##
6 ## This program is free software; you can redistribute it and/or modify
7 ## it under the terms of the GNU General Public License as published by
8 ## the Free Software Foundation; either version 2 of the License, or
9 ## (at your option) any later version.
10 ##
11 ## This program is distributed in the hope that it will be useful,
12 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 ## GNU General Public License for more details.
15 ##
16 ## You should have received a copy of the GNU General Public License
17 ## along with this program; if not, write to the Free Software
18 ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
20 #   queue = Queue.new
21 #   timeout(5) do
22 #     queue.deq
23 #   end
24 #
25 # is not good since not all of stdlib is safe with respect to 
26 # asynchronous exceptions.
27 # This class is a safe implementation.
28 # See: http://www.ruby-forum.com/topic/107864
29 #
30
31 require 'monitor'
32
33 module ShogiServer
34
35 class TimeoutQueue
36   def initialize(timeout=20)
37     @timeout = 20 # sec
38     @queue = []
39     @mon  = Monitor.new
40     @cond = @mon.new_cond
41   end
42
43   def enq(msg)
44     @mon.synchronize do
45       @queue.push(msg)
46       @cond.broadcast
47     end
48   end
49
50   #
51   # @return :timeout if timeout
52   #
53   def deq
54     timeout_flg = false
55     ret = :timeout
56     @mon.synchronize do
57       if @queue.empty?
58         unless @cond.wait(15)
59           #timeout
60           timeout_flg = true
61         end
62       end
63       if !timeout_flg && !@queue.empty?
64         ret = @queue.shift
65       end
66     end # synchronize
67     return ret
68   end
69
70   def empty?
71     ret = true
72     @mon.synchronize do
73       ret = @queue.empty?
74     end
75     return ret
76   end
77
78   def get_messages
79     ret = nil
80     @mon.synchronize do
81       ret = @queue.dup
82     end
83     return ret
84   end
85
86 end
87
88 end