同步访问分配的内存 [英] synchronizing access to allocated memory

查看:82
本文介绍了同步访问分配的内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以同步对已分配内存中每个元素的访问.例如,如果我使用以下代码分配内存

int* counters = new int[10];

有一种方法可以单独同步每个计数器的修改(能够同时修改counter [0],counters [1] ... counters [9]),以便对counter [ 0]在线程更新特定计数器(计数器[0])之前,释放锁以更新计数器[9]和其他计数器之前,不会阻塞计数器[9]?这些计数器没有关系,并且不依赖于与其他计数器的任何共享数据吗?

解决方案

如果要避免使用互斥锁进行同步,则需要查看<atomic>标头工具.

假设计数器"数组只是跟踪一定数量计数的一种方法,可以使用std::atomic<int> counters[10]来完成,并且可以通过调用counters[i].fetch_add(1, std::memory_order_relaxed)以线程安全的方式递增每个计数器. /p>

正如用户Barmar指出的那样,std::atomic<int>也可以在内部使用互斥量.这是依赖于实现的,可以通过调用std::atomic<int>实例的is_lock_free()成员函数来查询.在我的实现中,std::atomic<int>实例是无锁的.

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?

解决方案

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.

这篇关于同步访问分配的内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆