我的实现为后人
#include <vector>
#include <functional>
#include <tbb/mutex.h> //could of course use std::mutex instead, if available
template <typename Key, typename Hash = std::hash<Key>>
class mutex_map
{
public:
typedef Key key_type;
typedef tbb::mutex value_type;
static const std::size_t default_bucket_count = 16;
private:
std::vector<value_type> mutexes;
Hash hash;
public:
mutex_map(
std::size_t bucket_count = default_bucket_count,
const Hash& hash = Hash())
: hash(hash)
{
mutexes.resize(bucket_count);
}
std::size_t size() const
{
return mutexes.size();
}
value_type& get(const Key& key)
{
auto n = hash(key) % size();
n += (n < 0) * size();
return mutexes[n];
}
};
您可能需要使用原子标志,而不是互斥的,如果你不关心两个并发写入,或者一个写进来,而另一个正在进行中。 – 2013-05-11 01:30:06