假设我有两个连接,每个连接都有各自strand
的线程安全性。这些连接不是单独运行的,它们可以以某种方式相互交谈。在此通信阶段,处理程序必须同步,这样没有两个处理程序可以同时修改连接对象。
那么,为了实现这一点,我可以strand::wrap
嵌套使用两个 s 吗?
例如,考虑以下伪代码:
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???
});
}
};