我正在尝试寻找更好的方法来处理轮询套接字(fd)的事件。我坚持这样做是为了用一个不同的pollfd来利用poll()函数:
#define out std::cout
#define el std::endl
#define line(string) out<<string<<el
class int_t
{
private:
int _int;
int _owner;
public:
operator int() const;
int_t();
int_t(const int& in);
int_t& operator=(const int& in);
int_t operator|(const int& in) const;
int_t operator&(const int& in) const;
/*
...
...
*/
void setowner(const int& fd);
~int_t();
};
int_t::operator int() const
{
return this->_int;
}
int_t::int_t()
{
this->_int = 0;
this->_owner = 0;
}
int_t::int_t(const int& in)
{
this->_int = in;
this->_owner = 0;
}
int_t& int_t::operator=(const int& in)
{
line("operator '=' called"<<" owner:"<<this->_owner);
this->_int = in;
return *this;
}
int_t int_t::operator|(const int& in) const
{
line("operator '|' called"<<" owner:"<<this->_owner);
return (this->_int|in);
}
int_t int_t::operator&(const int& in) const
{
line("operator '&' with arg called"<<" owner:"<<this->_owner);
return (this->_int&in);
}
/*
...
...
*/
void int_t::setowner(const int& fd)
{
this->_owner = fd;
}
int_t::~int_t()
{
this->_int = 0;
}
struct pollfd_other
{
// Valgrind returns me an error when i changing the type of the `revent` only
// but when i changing the type of the `event` and `revent` works without error
// and `poll()` gets the flags normally from the `event` if ill put for example
// a `POLLIN` flag.
int fd;
int_t events;
int_t revents;
void setowner(const int& pollfdowner){
this->fd = pollfdowner;
this->revents.setowner(pollfdowner);
}
};
int main(int argc,char* argv[])
{
Server server;
pollfd_other pfd[1];
pfd[0].setowner(server.socket);
::poll(reinterpret_cast<pollfd*>(&pfd),1,-1);
// ...
}作为整数和struct pollfd_other,class int_t工作得很好……但是poll()不会像访问类一样访问它来调用运算符...
这样做的目的是在struct pollfd_other的revents成员上调用操作符时创建一个线程。
有没有其他方法可以做到这一点?欢迎您的建议。
发布于 2011-08-14 05:56:20
这看起来非常复杂。如果您想将投票功能封装在对象中,请不要封装int,而是封装投票。如下所示:
class poller_callback {
public:
void handle_pollin(int fd) = 0;
};
class poller {
public:
poller(const vector<int>& fds);
void do_poll(const poller_callback& c)
{
// poll(&pfd, ...);
if(fd[i].revents & POLLIN) {
c.handle_pollin(fd[i].fd);
}
}
};
int main(void)
{
my_poller_callback my_handler;
// get fds
poller my_poller(fds);
do_poll(my_handler);
// ...
return 0;
}我就是这么做的。有一个封装poll()的类,它根据应该对事件执行的操作进行参数化。poller_callback是处理事件的对象的接口。然后,您可以编写在其handle_pollin中创建线程的my_poller_callback。
发布于 2011-08-14 06:44:27
在Linux上,我推荐使用epoll (http://kovyrin.net/2006/04/13/epoll-asynchronous-network-programming/,手册页)。它比poll/select快得多,也更容易使用,因为你可以为每个处理过的描述符标记一个指针。
https://stackoverflow.com/questions/7053472
复制相似问题