synchronizing access to allocated memory

我的梦境 提交于 2020-01-05 02:33:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!