Chr*_*ton 1 c c++ sockets timeout pthreads
我有以下问题需要解决.我想向许多"远程"服务器(实际上是我们控制的服务器场)发出大量请求.连接非常简单.发送一行,然后读回去的行.由于请求数量和服务器数量,我使用pthreads,每个请求一个.
使用阻塞套接字的天真方法不起作用; 偶尔,我会在'连接'中插入一个线程.我不能使用SIGALRM,因为我正在使用pthreads.我尝试将代码转换为O_NONBLOCK,但这使得读取单行的代码变得非常复杂.
我有什么选择?我正在寻找允许以下伪代码的最简单的解决方案:
// Inside a pthread
try {
req = connect(host, port);
req.writeln("request command");
while (line = req.readline()) {
// Process line
}
} catch TimeoutError {
// Bitch and complain
}
Run Code Online (Sandbox Code Playgroud)
我的代码是用C++编写的,我正在使用Boost.快速浏览一下Boost ASIO向我展示它可能不是正确的方法,但我可能错了. ACE远远超重,无法解决这个问题.
我看到了评论,我认为你可以使用boost :: asio和boost :: asio :: deadline_timer
代码片段:
void restart_timer()
{
timer_.cancel();
timer_.expires_from_now(boost::posix_time::seconds(5));
timer_.async_wait(boost::bind(&handleTimeout,
MyClass::shared_from_this(), boost::asio::placeholders::error));
}
Run Code Online (Sandbox Code Playgroud)
handleTimeout是一个回调函数,timer_boost :: asio :: deadline_timer和MyClass类似
class Y: public enable_shared_from_this<Y>
{
public:
shared_ptr<Y> f()
{
return shared_from_this();
}
}
Run Code Online (Sandbox Code Playgroud)
您可以在连接读/写之前调用restart_timer
更多信息有关share_from_this()
| 归档时间: |
|
| 查看次数: |
2448 次 |
| 最近记录: |