1 #############################################################
2 # Author: Ingar M. Arntzen
3 #############################################################
6 This implements a thread hotel where threads block for asynchronous replies
7 after having made an non-blocking request. The thread hotel is typically used
8 to build a blocking API on top of a non-blocking.
13 #############################################################
15 #############################################################
19 """Threads wait in the Thread Hotel until the reply associated with a given
20 request ID is available."""
23 """Each thread is assigned his own room."""
25 self._bed = threading.Event()
31 def wakeup_call(self):
32 """Wake up sleeping thread."""
35 """Get the asynchronous reply."""
36 return (self._status, self._reply)
37 def set_reply(self, status, reply):
38 """Leave the asynchronous reply."""
44 self._lock = threading.Lock()
46 def _get_room(self, request_id):
47 """Get a room given a request_id.
48 The request id is assumed to be unique. """
49 if not self._rooms.has_key(request_id):
50 self._rooms[request_id] = ThreadHotel.Room()
51 return self._rooms[request_id]
53 def _leave_room(self, request_id):
54 """Leave room after having been woke up."""
55 del self._rooms[request_id]
57 def reserve(self, request_id):
58 """Reserve a room before the asynchronous request is
59 actually carried out."""
61 self._get_room(request_id)
64 def wait_reply(self, request_id):
65 """Wait for a reply given a unique request id."""
67 room = self._get_room(request_id)
68 status, reply = room.get_reply()
69 # Reply is available -> Return immedately
76 status, reply = room.get_reply()
78 self._leave_room(request_id)
82 def wakeup(self, request_id, status, reply):
83 """Deliver reply for given request id, thereby waking up
85 if self._rooms.has_key(request_id):
87 room = self._rooms[request_id]
88 room.set_reply(status, reply)
89 # Wake up potential visitor.
95 def is_waiting(self, request_id):
96 """Is threre a thread waiting for a given request id?"""
97 return self._rooms.has_key(request_id)