I\'ve been reading about the new C++11 memory model and I\'ve come upon the std::kill_dependency
function (§29.3/14-15). I\'m struggling to understand why
The usual use case of kill_dependency
arises from the following. Suppose you want to do atomic updates to a nontrivial shared data structure. A typical way to do this is to nonatomically create some new data and to atomically swing a pointer from the data structure to the new data. Once you do this, you are not going to change the new data until you have swung the pointer away from it to something else (and waited for all readers to vacate). This paradigm is widely used, e.g. read-copy-update in the Linux kernel.
Now, suppose the reader reads the pointer, reads the new data, and comes back later and reads the pointer again, finding that the pointer hasn't changed. The hardware can't tell that the pointer hasn't been updated again, so by consume
semantics he can't use a cached copy of the data but has to read it again from memory. (Or to think of it another way, the hardware and compiler can't speculatively move the read of the data up before the read of the pointer.)
This is where kill_dependency
comes to the rescue. By wrapping the pointer in a kill_dependency
, you create a value that will no longer propagate dependency, allowing accesses through the pointer to use the cached copy of the new data.