问题
Is there a way to synchronize access to each element in an allocated memory. For example, if I allocate memory using the following code
int* counters = new int[10];
is there a way to synchronize modification of each counter separately (being able to modify counters[0], counters[1]...counters[9] at the same time) so that modification of, let's say, counters[0] won't block counters[9] until the lock is released to update counters[9] and the other counters while a thread is updating a specific counter, counters[0]? The counters aren't related and don't depend on any shared data with the other counters?
回答1:
You need to look into the <atomic>
header facilities if you want to avoid using mutexes for synchronization.
Assuming your 'counters' array is simply a way to keep track of a certain number of counts, it can be done by using std::atomic<int> counters[10]
and each counter can be incremented in a thread safe way by calling counters[i].fetch_add(1, std::memory_order_relaxed)
.
As user Barmar has pointed out, std::atomic<int>
could also employ a mutex internally. This is implementation dependent and can be queried by calling the is_lock_free()
member function of a std::atomic<int>
instance. On my implementation, std::atomic<int>
instances are lock free.
回答2:
While array of mutexes is a natural solution, one should consider the implications. This is fine with arrays of 10 elements, but the number of mutexes is actually limited. If you have arrays of, say, 50 000 items (not that big at all) you will run out of mutexes.
来源:https://stackoverflow.com/questions/32510227/synchronizing-access-to-allocated-memory