template<typename T, typename RcuTraits>
class rcu::Variable< T, RcuTraits >
Read-Copy-Update variable.
- See also
- Based on ideas from http://www.drdobbs.com/lock-free-data-structures-with-hazard-po/184401890 with modified API.
A variable with MT-access pattern "very often reads, seldom writes". It is specially optimized for reads. On read, one obtains a ReaderPtr<T> from it and uses the obtained value as long as it wants to. On write, one obtains a WritablePtr<T> with a copy of the last version of the value, makes some changes to it, and commits the result to update current variable value (does Read-Copy-Update). Old version of the value is not freed on update, it will be eventually freed when a subsequent writer identifies that nobody works with this version.
Write transactions on the same rcu::Variable are mutually exclusive. With rcu::DefaultRcuTraits, rcu::SyncRcuTraits, and rcu::BlockingRcuTraits, concurrent writers wait and proceed one by one. rcu::Variable::StartWrite first acquires the writer mutex and then copies the latest committed value into its transaction, so a writer observes changes committed by preceding writers. The mutex is held until rcu::WritablePtr::Commit or rcu::WritablePtr destruction. The order in which concurrent writers acquire the mutex is unspecified. Readers don't acquire the writer mutex and may continue using older snapshots while a writer is active.
- Note
- rcu::ExclusiveRcuTraits requires the caller to guarantee that write operations on the same rcu::Variable never overlap. If another writer starts while a write transaction is active, an invariant violation is reported instead of waiting: debug builds abort, while release builds throw utils::InvariantError.
-
The writer mutex protects copying, construction, and publication of the internal RCU snapshot. It does not protect evaluation or copying of arguments before a write method is entered.
-
There is no way to create a "null" Variable.
Example usage:
constexpr int kOldValue = 1;
constexpr auto kOldString = "Old string";
constexpr int kNewValue = 2;
constexpr auto kNewString = "New string";
struct Data {
int x;
std::string s;
};
{
auto ro_ptr = data.
Read();
ASSERT_EQ(ro_ptr->x, kOldValue);
ASSERT_EQ(ro_ptr->s, kOldString);
}
{
ptr->x = kNewValue;
ptr->s = kNewString;
ptr.Commit();
}
- See also
- Synchronization Primitives
- Template Parameters
-
- Examples
- samples/config_service/main.cpp.
Definition at line 434 of file rcu.hpp.
template<typename T, typename RcuTraits>
template<typename... Args>
Obtain a smart pointer to a newly in-place constructed value, but does not replace the current one yet (in contrast with regular Emplace). First acquires the writer mutex, then constructs the internal replacement value. Owns the mutex until Commit or destruction. Function arguments are evaluated before the call and are not protected by this mutex.
Definition at line 496 of file rcu.hpp.