6 #include <msp/core/systemerror.h>
7 #include <msp/strings/format.h>
8 #include "eventobject.h"
10 #include "handle_private.h"
18 using namespace Msp::IO;
20 inline short int sys_poll_event(PollEvent event)
24 if(event&~(P_INPUT|P_PRIO|P_OUTPUT))
25 throw invalid_argument("sys_poll_event");
39 inline PollEvent poll_event_from_sys(int event)
41 PollEvent result = P_NONE;
47 result = result|P_INPUT;
49 result = result|P_PRIO;
51 result = result|P_OUTPUT;
53 result = result|P_ERROR;
59 inline PollEvent do_poll(EventObject &obj, PollEvent pe, int timeout)
65 DWORD ret = WaitForSingleObject(*obj.get_event_handle(), timeout);
66 if(ret==WAIT_OBJECT_0)
68 else if(ret==WAIT_FAILED)
69 throw system_error("WaitForSingleObject");
73 pollfd pfd = { *obj.get_event_handle(), sys_poll_event(pe), 0 };
75 int ret = ::poll(&pfd, 1, timeout);
81 throw system_error("poll");
84 return poll_event_from_sys(pfd.revents);
94 struct Poller::Private
97 vector<HANDLE> handles;
114 void Poller::set_object(EventObject &obj, PollEvent ev)
116 // Verify that the object has an event handle
118 obj.get_event_handle();
120 EventMap::iterator i = objects.find(&obj);
133 if(objects.size()>=MAXIMUM_WAIT_OBJECTS)
134 throw logic_error("Maximum number of wait objects reached");
136 objects.insert(EventMap::value_type(&obj, ev));
147 int Poller::poll(const Time::TimeDelta &timeout)
149 if(timeout<Time::zero)
150 throw invalid_argument("Poller::poll");
152 return do_poll(static_cast<int>(timeout/Time::msec));
155 void Poller::rebuild_array()
158 priv->handles.clear();
160 for(EventMap::iterator i=objects.begin(); i!=objects.end(); ++i)
161 priv->handles.push_back(*i->first->get_event_handle());
165 for(EventMap::iterator i=objects.begin(); i!=objects.end(); ++i)
168 p.fd = *i->first->get_event_handle();
169 p.events = sys_poll_event(i->second);
170 priv->pfd.push_back(p);
174 objs_changed = false;
177 int Poller::do_poll(int timeout)
188 DWORD ret = WaitForMultipleObjects(priv->handles.size(), &priv->handles.front(), false, timeout);
189 if(/*ret>=WAIT_OBJECT_0 &&*/ ret<WAIT_OBJECT_0+priv->handles.size())
191 EventMap::iterator i = objects.begin();
192 advance(i, ret-WAIT_OBJECT_0);
193 poll_result.push_back(Slot(i->first, i->second));
197 else if(ret==WAIT_FAILED)
198 throw system_error("WaitForMultipleObjects");
202 int ret = ::poll(&priv->pfd.front(), priv->pfd.size(), timeout);
208 throw system_error("poll");
212 EventMap::iterator j = objects.begin();
213 for(vector<pollfd>::iterator i=priv->pfd.begin(); (i!=priv->pfd.end() && n>0); ++i, ++j)
216 poll_result.push_back(Slot(j->first, poll_event_from_sys(i->revents)));
225 PollEvent poll(EventObject &obj, PollEvent pe)
227 return do_poll(obj, pe, -1);
230 PollEvent poll(EventObject &obj, PollEvent pe, const Time::TimeDelta &timeout)
232 if(timeout<Time::zero)
233 throw invalid_argument("poll");
235 return do_poll(obj, pe, static_cast<int>(timeout/Time::msec));