簡體   English   中英

在兩個線程之間共享deadline_timer

[英]Share deadline_timer between two threads

我需要在兩個線程之間共享一個boost :: deadline_timer。 boost文檔說“共享實例不是線程安全的”。 這是一個示例代碼:

ClassA : public enable_shared_from_this<ClassA>{

  ClassA()
  {
    m_timer = new boost::deadline_timer(m_io_service);
  }

  destroy()
  {
    m_timer->cancel();
    delete m_timer;
    m_timer = NULL;
  }

  thread_method()
  {
    m_timer->expire_from_now(...);
    m_timer->async_wait(...);
  }

   run()
   {
     boost::thread t(ClassA::thread_method, shared_from_this);
   }
}

我的問題是“要同步destroy()和thread_method()之間的定時器訪問,我可以使用boost :: atomic嗎?

標題:

boost::atomic<boost::deadline_timer*> m_timer;

構造函數:

m_timer = new boost::deadline_timer(m_io_service);

它是線程安全的嗎?

謝謝。

不,那沒有用。

原子只使指針的存儲/加載不可分割。 當你取消引用它時,你只是直接訪問deadline_timer ,不同步。

所以你也可以

  • 只是傳統的線程同步所有訪問截止時間計時器(例如使用mutex

  • 使用Asio strand創建一個“邏輯”執行線程,並注意只從該鏈訪問死區計時器。

strand方法可能更有效,但需要您更准確地考慮執行流程,以免意外創建數據爭用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM