【发布时间】:2018-02-15 02:56:26
【问题描述】:
假设我有两个连接,每个连接都有各自的strand 以保证线程安全。这些连接不是单独运行的,它们可以以某种方式相互交谈。在此通信阶段,处理程序必须同步,这样任何两个处理程序都不能同时修改连接对象。
那么,为了实现这一点,我可以嵌套使用两个strand::wraps 吗?
例如,考虑以下伪代码:
class connection /* connection actually uses shared_ptr's to ensure lifetime */
{
public:
connection *other /* somehow set */;
strand strnd /* somehow initialized correctly */;
socket sock /* somehow initialized correctly */;
streambuf buf;
int a /* shared variable */;
void trigger_read() // somewhat triggered
{
// since operations on sock are not thread-safe, use a strand to
// synchronise them
strnd.post([this] {
// now consider the following code,
async_read_until(sock, buf, '\n',
this->strnd.wrap /* wrapping by this->strnd is for sure */([](...) {
// depending on the data, this handler can alter both other
// and this
other->a ++; // not safe
this->a --; // this is safe as protected by this->strnd
}));
// can protect them both by something like,
async_read_until(sock, buf, '\n',
this->strnd.wrap(other->strnd.wrap([](...) {
// depending on the data, this handler can alter both other
// and this
other->a ++; // not safe
this->a --; // this is safe as protected by this->strnd
})));
// this???
});
}
};
【问题讨论】:
-
这是一个很难还是不好的问题:/
-
哇。你应该买更多的耐心,马上。
-
我喜欢这个问题,但回答起来并不容易(否则 OP 应该自己回答)。反对票不是我的,我用反对票反对。
-
@sehe 谢谢。如果问题很好,那就太好了!我觉得它可以帮助我进一步了解图书馆。兴奋地等待您的答复。
标签: c++ boost boost-asio asio