Reputation: 3738
several (2 or more) client threads need to run at a high frequency, but once every 1 minute a background service thread updates a variable used by the main threads.
whats is the best method of locking a variable -- in fact, a vector -- during the small moment of update with little impact on the client threads.
there is no need to protect the vector during 'normal' (no background thread) operation since all threads utilize the values.
boost::thread is used with a endless while loop to update the vector and sleep for 60 seconds.
Upvotes: 1
Views: 196
Reputation: 393613
This seems like a good occasion for a Reader-Writer lock. All the clients lock the vector for reading only, and the background service thread locks it for writing only once every minute.
SharedLockable
concept from c++14 which is implemented in Boost Thread as boost::shared_mutex
The class
boost::shared_mutex
provides an implementation of a multiple-reader / single-writer mutex. It implements theSharedLockable
concept.Multiple concurrent calls to
lock()
,try_lock()
,try_lock_for()
,try_lock_until()
,timed_lock()
,lock_shared()
,try_lock_shared_for()
,try_lock_shared_until()
,try_lock_shared()
andtimed_lock_shared()
are permitted.
That said, depending on your actual platform and CPU model you could get more lucky with an atomic variable.
If it's a primitive value, just using boost::atomic_int
or similar would be fine. For a vector, consider using std::shared_ptr (which has atomic support).See e.g.
You can also do without the dynamic allocation (although, you're using vector already) by using two vectors, and switching a reference to the "actual" version atomically.
Upvotes: 1