我有一個運行在boost::asio::io_service
有一些屬性的對象。類似的東西:如何等待一個asio處理程序?
class Foo
{
private:
// Not an int in my real code, but it doesn't really matter.
int m_bar;
boost::asio::io_service& m_io_service;
boost::asio::strand m_bar_strand;
};
m_bar
是從一個即通過鏈m_bar_strand
稱爲處理才能使用。這使我不會從這些處理程序中鎖定。
從運行io_service::run()
我寫了一個asynchronous_setter,像這樣一個線程之外設置m_bar
屬性:
class Foo
{
public:
void async_get_bar(function<void (int)> handler)
{
m_bar_strand.post(bind(&Foo::do_get_bar, this, handler));
}
void async_set_bar(int value, function<void()> handler)
{
m_bar_strand.post(bind(&Foo::do_set_bar, this, value, handler));
}
private:
void do_get_bar(function<void (int)> handler)
{
// This is only called from within the m_bar_strand, so we are safe.
// Run the handler to notify the caller.
handler(m_bar);
}
void do_set_bar(int value, function<void()> handler)
{
// This is only called from within the m_bar_strand, so we are safe.
m_bar = value;
// Run the handler to notify the caller.
handler();
}
int m_bar;
boost::asio::io_service& m_io_service;
boost::asio::strand m_bar_strand;
};
這工作完全,但現在我想寫的set_bar
同步版本設置價值和回報只有當集合有效。它仍然必須保證有效設置將在m_bar_strand
內發生。理想情況下,可重入。
我可以想象解決方案的信號量將被修改從處理程序內,但我所提出的一切似乎hackish,真的不優雅。在Boost/Boost Asio中有什麼可以允許這樣的事情嗎?
您將如何繼續實施此方法?
空隙sync_set_bar(int值,函數處理程序){ m_bar = value; handler();}繼續make m_bar boost :: atomic 。 –
IdeaHat
(儘管我不確定在m_bar上需要什麼同步控制,所以我可能只是把你搞砸了)當事情不是異步時,不需要使用asio。 – IdeaHat
@MadScienceDreams:'m_bar'值(無論其類型)只能在** m_bar_strand中運行的處理程序中從**更改(或訪問)。這可以防止不使用互斥體的競爭條件,並且非常好。我只想將異步調用轉換爲同步調用。 – ereOn