提高线程互斥阵列 [英] boost threads mutex array

查看:179
本文介绍了提高线程互斥阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是,我有多个线程更新的块矩阵。
多个线程可在同一时间内更新不相交块但一般可以有竞争条件。现在矩阵使用单锁锁住。

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 now matrix is locked using single lock.

现在的问题是,是否有可能(如果是,怎么样?)
实施锁的有效阵列,使得仅矩阵的部分在时间也许锁定

The question is, is it possible (and if it is, how?) to implement an efficient array of locks, so that only portions of matrix maybe locked at a time.

问题的矩阵可以得到相当大,在50 ^ 2个街区秩序。我最初的猜测是动态地分配使用互斥的矢量/图

The matrix in question can get rather large, on order of 50^2 blocks. my initial guess is to use dynamically allocate vector/map of mutexes.

是不是好办法?
是它更好地使用多个条件变量来代替?
 有没有更好的办法?

Is it good approach? is it better to use multiple condition variables instead? is there better approach?

感谢您

推荐答案

使用一个单一的锁。但是,而不是用它来保护整个矩阵用它来守卫的std ::设置(或的boost :: unordered_set ),它说该块被锁定。

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".

这样的事情。

class Block;

class Lock_block
{
public:
   Lock_block( Block& block ) : m_block(&block)
   {
      boost::unique_lock<boost::mutex> 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<boost::mutex> 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<Block*> s_locked;
};

这篇关于提高线程互斥阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆