Self inflicted wounds using cx_freeze
[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
7 class Sleeper(multiprocessing.Process):
8         def __init__(self, timeout):
9                 multiprocessing.Process.__init__(self)
10                 self.timeout = timeout
11
12         def run(self):
13                 time.sleep(self.timeout)
14
15
16 class Worker(multiprocessing.Process):
17         def __init__(self, function, args, q):
18                 multiprocessing.Process.__init__(self)
19                 self.function = function
20                 self.args = args
21                 self.q = q
22
23         def run(self):
24                 #print str(self) + " runs " + str(self.function) + " with args " + str(self.args) 
25                 self.q.put(self.function(*self.args))
26                 
27                 
28
29 def TimeoutFunction(function, args, timeout):
30         q = multiprocessing.Queue()
31         w = Worker(function, args, q)
32         s = Sleeper(timeout)
33         w.start()
34         s.start()
35         while True: # Busy loop of crappyness
36                 if not w.is_alive():
37                         s.terminate()
38                         result = q.get()
39                         w.join()
40                         #print "TimeoutFunction gets " + str(result)
41                         return result
42                 elif not s.is_alive():
43                         w.terminate()
44                         s.join()
45                         raise Exception("UNRESPONSIVE")
46
47         
48                 
49
50 # A player that wraps another player and times out its moves
51 # Uses threads
52 # A (crappy) alternative to the use of select()
53 class TimeoutPlayer(Player):
54         def __init__(self, base_player, timeout):
55                 Player.__init__(self, base_player.name, base_player.colour)
56                 self.base_player = base_player
57                 self.timeout = timeout
58                 
59         def select(self):
60                 return TimeoutFunction(self.base_player.select, [], self.timeout)
61                 
62         
63         def get_move(self):
64                 return TimeoutFunction(self.base_player.get_move, [], self.timeout)
65
66         def update(self, result):
67                 return TimeoutFunction(self.base_player.update, [result], self.timeout)
68
69         def quit(self, final_result):
70                 return TimeoutFunction(self.base_player.quit, [final_result], self.timeout)

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