2 #include <msp/strings/formatter.h>
3 #include <msp/time/units.h>
11 using namespace Msp::IO;
13 inline int sys_poll_event(PollEvent event)
17 if(event&~(P_INPUT|P_PRIO|P_OUTPUT))
18 throw InvalidParameterValue("Invalid poll events");
32 inline PollEvent poll_event_from_sys(int event)
34 PollEvent result = P_NONE;
37 // Stop the compiler from complaining about unused parameter
41 result = result|P_INPUT;
43 result = result|P_PRIO;
45 result = result|P_OUTPUT;
47 result = result|P_ERROR;
53 inline PollEvent do_poll(Base &obj, PollEvent pe, int timeout)
59 DWORD ret = WaitForSingleObject(obj.get_event_handle(), timeout);
60 if(ret==WAIT_OBJECT_0)
62 else if(ret==WAIT_FAILED)
63 throw SystemError("Poll failed", GetLastError());
67 pollfd pfd = {obj.get_event_handle(), sys_poll_event(pe), 0};
69 int ret = ::poll(&pfd, 1, timeout);
75 throw SystemError("Poll failed", errno);
78 return poll_event_from_sys(pfd.revents);
91 void Poller::set_object(Base &obj, PollEvent ev)
93 // Verify that the object has an event handle
95 obj.get_event_handle();
97 SlotMap::iterator i = objects.find(&obj);
101 i->second.events = ev;
110 if(objects.size()>=MAXIMUM_WAIT_OBJECTS)
111 throw InvalidState("Maximum number of wait objects reached");
113 objects.insert(SlotMap::value_type(&obj, Slot(&obj, ev)));
124 int Poller::poll(const Time::TimeDelta &timeout)
126 if(timeout<Time::zero)
127 throw InvalidParameterValue("Invalid timeout");
129 return do_poll(static_cast<int>(timeout/Time::msec));
132 void Poller::rebuild_pfd()
138 for(SlotMap::iterator i=objects.begin(); i!=objects.end(); ++i)
140 p.fd = i->second.object->get_event_handle();
142 p.events = sys_poll_event(i->second.events);
150 int Poller::do_poll(int timeout)
161 DWORD ret = WaitForMultipleObjects(pfd.size(), &pfd.front().fd, false, timeout);
162 if(/*ret>=WAIT_OBJECT_0 &&*/ ret<WAIT_OBJECT_0+pfd.size())
164 SlotMap::iterator i = objects.begin();
165 advance(i, ret-WAIT_OBJECT_0);
166 poll_result.push_back(Slot(i->second.object, i->second.events));
170 else if(ret==WAIT_FAILED)
171 throw SystemError("Poll failed", GetLastError());
175 int ret = ::poll(&pfd.front(), pfd.size(), timeout);
181 throw SystemError("Poll failed", errno);
185 SlotMap::iterator j = objects.begin();
186 for(std::vector<pollfd>::iterator i=pfd.begin(); (i!=pfd.end() && n>0); ++i,++j)
189 poll_result.push_back(Slot(j->second.object, poll_event_from_sys(i->revents)));
198 PollEvent poll(Base &obj, PollEvent pe)
200 return do_poll(obj, pe, -1);
203 PollEvent poll(Base &obj, PollEvent pe, const Time::TimeDelta &timeout)
205 if(timeout<Time::zero)
206 throw InvalidParameterValue("Invalid timeout");
208 return do_poll(obj, pe, static_cast<int>(timeout/Time::msec));