boost threads mutex array

后端 未结 2 1616
南旧
南旧 2021-01-05 15:57

My problem is, I have block matrix updated by multiple threads. Multiple threads may be updating disjoint block at a time but in general there may be race conditions. right

2条回答
  •  被撕碎了的回忆
    2021-01-05 16:34

    Use a single lock. But instead of using it to protect the entire matrix use it to guard a std::set (or a boost::unordered_set) which says which blocks are "locked".

    Something like this.

    class Block;
    
    class Lock_block
    {
    public:
       Lock_block( Block& block ) : m_block(&block)
       {
          boost::unique_lock lock(s_mutex);
          while( s_locked.find(m_block) != s_locked.end() )
          {
             s_cond.wait(lock);
          }
          bool success = s_locked.insert(m_block).second;
          assert(success);
       }
    
       ~Lock_block()
       {
          boost::lock_guard lock(s_mutex);
          std::size_t removed = s_locked.erase(m_block);
          assert(removed == 1);
          s_cond.notify_all();
       }
    private:
       Block* m_block;
    
       static boost::mutex s_mutex;
       static boost::condition s_cond;
       static std::set s_locked;
    };
    

提交回复
热议问题