Pseudocode:
Function1_vector_copy () {
vectora = vectorb;
}
Function2_vector_search() {
find k in vectora;
}
The program is multi-threaded. While many threads may search , vector copying is done only by a single thread but at occasional times. The problem is whatever it may, vector_search should not fail. Vector_copy can be deferred but vector_search should not be. Its a no delay, no failure pattern. The problem is the shared variable vectora which has to be persistent, so that vector_search is not failed at all. What is an optimal way in achieving this ?
Edit :
Using an answer for another question
boost::shared_mutex _access;
Function1_vector_copy() {
// get upgradable access
boost::upgrade_lock lock(_access);
// get exclusive access
boost::upgrade_to_unique_lock uniqueLock(lock);
// now we have exclusive access
vectora.swap(vectorb);
}
Function2_vector_search() {
// get shared access
boost::shared_lock lock(_access);
// now we have shared access
find k in vectora ;
}
If a thread with upgradable ownership tries to upgrade whilst other threads have shared ownership, the attempt will fail and the thread will block until exclusive ownership can be acquired. --boost-documentation
The trick is the vector copy is done asynchronously and it will happen after exclusive ownership is acquired. So vector copy does eventually happen but deferred and indeed vector copy is also a non-failure operation but delayed which is okay for me. There will be a lock somehow for synchronization and we will block for a milli second atleast. But the advantage of using this swap will result in lower time of that making it negligible.
The rest is left as an exercise for the reader.
UPDATE: Summarizing the comments below...
First of all I should make clear that the original
swap(...)
call above was intended as pseudo-code, not necessarily to be taken literally. I didn't know exactly whatVectorType
was (and technically still don't). I assumed that you would intend on doing as efficient a swap() as was possible. It was pseudo-code after all...In any case,
std::swap()
is specialized for all container types in the C++ standard library. So ifVectorType
is actuallystd::vector<UDT>
, thenswap(tmp,vectora);
should be both optimal and work without modification (relying on Koenig lookup to resolve the symbol).