cgi-script almost working
[progcomp2013.git] / qchess / src / timeout_player.py
1 import multiprocessing
2
3 # Hacky alternative to using select for timing out players
4
5 # WARNING: Do not wrap around HumanPlayer or things breakify
6 # WARNING: Do not use in general or things breakify
7
8 class Sleeper(multiprocessing.Process):
9         def __init__(self, timeout):
10                 multiprocessing.Process.__init__(self)
11                 self.timeout = timeout
12
13         def run(self):
14                 time.sleep(self.timeout)
15
16
17 class Worker(multiprocessing.Process):
18         def __init__(self, function, args, q):
19                 multiprocessing.Process.__init__(self)
20                 self.function = function
21                 self.args = args
22                 self.q = q
23
24         def run(self):
25                 #print str(self) + " runs " + str(self.function) + " with args " + str(self.args)
26                 #try:
27                 self.q.put(self.function(*self.args))
28                 #except IOError:
29                 #       pass
30                 
31                 
32
33 def TimeoutFunction(function, args, timeout):
34         q = multiprocessing.Queue()
35         w = Worker(function, args, q)
36         s = Sleeper(timeout)
37         w.start()
38         s.start()
39         while True: # Busy loop of crappyness
40                 if not w.is_alive():
41                         s.terminate()
42                         result = q.get()
43                         w.join()
44                         #print "TimeoutFunction gets " + str(result)
45                         return result
46                 elif not s.is_alive():
47                         w.terminate()
48                         s.join()
49                         raise Exception("TIMEOUT")
50                 time.sleep(0.1)
51         
52                 
53
54 # A player that wraps another player and times out its moves
55 # Uses threads
56 # A (crappy) alternative to the use of select()
57 class TimeoutPlayer(Player):
58         def __init__(self, base_player, timeout):
59                 Player.__init__(self, base_player.name, base_player.colour)
60                 self.base_player = base_player
61                 self.timeout = timeout
62                 
63         def select(self):
64                 return TimeoutFunction(self.base_player.select, [], self.timeout)
65                 
66         
67         def get_move(self):
68                 return TimeoutFunction(self.base_player.get_move, [], self.timeout)
69
70         def update(self, result):
71                 return TimeoutFunction(self.base_player.update, [result], self.timeout)
72
73         def quit(self, final_result):
74                 return TimeoutFunction(self.base_player.quit, [final_result], self.timeout)

UCC git Repository :: git.ucc.asn.au