多线程-在数组中我应该保护什么? [英] Multithreading - In an array what should I protect?

查看:87
本文介绍了多线程-在数组中我应该保护什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一些具有全局数组的代码,可以通过两个线程访问该数组以进行阅读.

I'm working on some code that has a global array that can be accessed by two threads for reading writing purposes.

将不会读取或写入一系列索引的批处理,因此我试图确定是应该锁定整个数组还是仅锁定当前使用的数组索引.

There will be no batch processing where a range of indexes are read or written, so I'm trying to figure out if I should lock the entire array or only the array index I am currently using.

最简单的解决方案是将数组视为CS,并在其周围放置一个较大的胖锁,但是我可以避免这种情况,而只锁一个索引吗?

The easiest solution would be to consider the array a CS and put a big fat lock around it, but can I avoid this and just lock an index?

干杯.

推荐答案

锁定一个索引意味着您可以跟踪哪个线程正在访问数组的哪个部分.跟踪此信息(在读取和写入线程之间共享)意味着您对该信息有一个锁定.因此,您仍将获得全局锁定. 在这种情况下,我认为最有效的方法是: -使用读/写锁 -或将大型数组分成几个子集,每个子​​集使用不同的锁.

Locking one index implies that you can keep track of which thread is accessing what part of the array. Keeping track of this information, which is shared between the reading and the writing thread, implies that you have one lock around this information. So, you still end up with a global lock. In this situation, I think that the most efficient approaches are: - using a reader/writer lock - or dividing the big array into a few subsets, each subset using a distinct lock.

这篇关于多线程-在数组中我应该保护什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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