我对用户空间 RCU(读取-复制-更新)非常感兴趣,并尝试通过 tr1::shared_ptr 模拟一个,这是代码,虽然我真的是并发编程的新手,请高手帮忙我来复习?
基本思想是,reader 调用 get_reading_copy() 来获取当前受保护数据的指针(假设它是第一代,或 G1)。writer 调用 get_updating_copy() 获取 G1 的副本(假设是 G2),并且只允许一个 writer 进入临界区。更新完成后, writer 调用 update() 进行交换,并使 m_data_ptr 指向 G2 数据。正在进行的读取器和写入器现在持有 G1 的 shared_ptr(s),读取器或写入器最终将释放 G1 数据。
任何新读者都会得到指向 G2 的指针,而新的写入者会得到 G2 的副本(假设它是 G3)。G1可能还没有发布,所以多代数据可能并存。
template <typename T>
class rcu_protected
{
public:
typedef T type;
typedef const T const_type;
typedef std::tr1::shared_ptr<type> rcu_pointer;
typedef std::tr1::shared_ptr<const_type> rcu_const_pointer;
rcu_protected() : m_is_writing(0),
m_is_swapping(0),
m_data_ptr (new type())
{}
rcu_const_pointer get_reading_copy ()
{
spin_until_eq (m_is_swapping, 0);
return m_data_ptr;
}
rcu_pointer get_updating_copy ()
{
spin_until_eq (m_is_swapping, 0);
while (!CAS (m_is_writing, 0, 1))
{/* do sleep for back-off when exceeding maximum retry times */}
rcu_pointer new_data_ptr(new type(*m_data_ptr));
// as spin_until_eq does not have memory barrier protection,
// we need to place a read barrier to protect the loading of
// new_data_ptr not to be re-ordered before its construction
_ReadBarrier();
return new_data_ptr;
}
void update (rcu_pointer new_data_ptr)
{
while (!CAS (m_is_swapping, 0, 1))
{}
m_data_ptr.swap (new_data_ptr);
// as spin_until_eq does not have memory barrier protection,
// we need to place a write barrier to protect the assignments of
// m_is_writing/m_is_swapping be re-ordered bofore the swapping
_WriteBarrier();
m_is_writing = 0;
m_is_swapping = 0;
}
private:
volatile long m_is_writing;
volatile long m_is_swapping;
rcu_pointer m_data_ptr;
};