"以原子"更新整个数组 [英] "Atomically" update an entire array

查看:169
本文介绍了"以原子"更新整个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个编写器线程和单个读者线程来更新和处理数组池(存储在map中的引用)。写入与读取的比率几乎为5:1(写入延迟是一个问题)。

I have a single writer thread and single reader thread to update and process a pool of arrays(references stored in map). The ratio of writes to read is almost 5:1(latency of writes is a concern).

写入器线程需要更新池中数组的少数元素在某些事件上。整个写操作(所有元素)都需要是原子的。

The writer thread needs to update few elements of an array in the pool based on some events. The entire write operation(all elements) needs to be atomic.

如果编写器线程正在更新它,我想确保读者线程读取先前更新的数组(类似于volatile但是在整个阵列而不是单个领域)。基本上,我可以负担得起读取陈旧的值而不是阻止。

I want to ensure that reader thread reads the previous updated array if writer thread is updating it(something like volatile but on entire array rather than individual fields). Basically, I can afford to read stale values but not block.

此外,由于写入频繁,创建新对象或锁定整个对象真的很昂贵读/写时的数组。

Also, since the writes are so frequent, it would be really expensive to create new objects or lock the entire array while read/write.

是否有更高效的数据结构可供使用或使用更便宜的锁?

Is there a more efficient data structure that could be used or use cheaper locks ?

推荐答案

另一个想法,假设数组只包含20个双打。

Another idea, given that the array contains only 20 doubles.

有两个数组,一个用于写入,一个用于读取。

Have two arrays, one for write, one for read.

读取器在读取期间锁定读取数组。

Reader locks the read array during read.

read()
    lock();
    read stuff
    unlock();

Writer首先修改写入数组,然后 tryLock 读取数组,如果锁定失败,罚款,write()返回;如果锁定成功,则将写入数组复制到读取数组,然后释放锁定。

Writer first modifies the write array, then tryLock the read array, if locking fails, fine, write() returns; if locking succeeds, copy the write array to the read array, then release the lock.

write()
    update write array
    if tryLock()
        copy write array to read array
        unlock()

读者可以被阻止,但仅限于复制20个双打所需的时间,这是短的。

Reader can be blocked, but only for the time it takes to copy the 20 doubles, which is short.

读者应使用自旋锁,如执行{} while(tryLock()== false); 以避免被暂停。

Reader should use spin lock, like do{}while(tryLock()==false); to avoid being suspended.

这篇关于"以原子"更新整个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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