简体   繁体   English

从阵列同时读取是否是线程安全的?

[英]Are simultaneous reads from an array thread-safe?

I have an array which contains integer values declared like this: 我有一个数组,其中包含声明如下的整数值:

int data[] = new int[n];

Each value needs to be processed and I am splitting the work into pieces so that it can be processed by separate threads. 每个值都需要处理,我将工作分成几部分,以便它可以由不同的线程处理。 The array will not be modified during processing. 处理期间不会修改数组。

Can all the processing threads read separate parts of the array concurrently? 所有处理线程可以同时读取数组的不同部分吗? Or do I have to use a lock? 或者我必须使用锁?

In other words: is this work order thread-safe? 换句话说:这个工单是否是线程安全的?

Array is created and filled
Threads are created and started
Thread 0 reads data[0..3]
Thread 1 reads data[4..7]
Thread 2 reads data[8..n]

Reading contents of an array (or any other collection, fields of an object, etc.) by multiple threads is thread-safe provided that the data is not modified in the meantime. 通过多个线程读取数组(或任何其他集合,对象的字段等)的内容是线程安全的,前提是在此期间不修改数据。

If you fill the array with data to process and pass it to different threads for reading, then the data will be properly read and no data race will be possible. 如果用数据填充数组进行处理并将其传递给不同的线程进行读取,那么将正确读取数据并且不会有数据争用。

Note that this will only work if you create the threads after you have filled the array . 请注意, 这只有在填充数组后创建线程时才有效 If you pass the array for processing to some already existing threads without synchronization, the contents of the array may not be read correctly. 如果将数组传递给某些已存在的线程而没有同步,则可能无法正确读取数组的内容。 In such case the method in which the thread obtains the reference to the array should be synchronized, because a synchronized block forces memory update between threads. 在这种情况下,线程获得对数组的引用的方法应该是同步的,因为同步块强制线程之间的内存更新。

On a side note: using an immutable collection may be a good idea. 旁注:使用不可变集合可能是个好主意。 That way you ensure no modification is even possible. 这样你就不会有任何修改。 I would sugges using such wrapper. 我建议使用这样的包装器。 Check the java.util.concurrent.atomic package, there should be something you can use. 检查java.util.concurrent.atomic包,应该有一些你可以使用的东西。

只要线程不修改数组中的内容,就可以从多个线程中读取数组。

If you ensure all the threads are just reading, its thread safe. 如果确保所有线程都只是读取,则其线程安全。 Though you should not be relying on that fact alone and try to make your array immutable via a wrapper. 虽然你不应该单独依赖这个事实alone并试图通过包装器使你的数组​​不可变。

Sure, if you just want to read it, pass the array to the threads when you create them. 当然,如果您只想阅读它,请在创建时将数组传递给线程。 There won't be any problem as long as you don't modify it. 只要您不修改它就不会有任何问题。

从数组数组中读取是线程安全操作,但如果您要修改数组而不是考虑使用类AtomicIntegerArray

Consider populating a ConcurrendLinkedQueue and have each thread pull from it. 考虑填充ConcurrendLinkedQueue并让每个线程从中拉出。 This would ensure that there are no concurrency issues. 这将确保不存在并发问题。

Your threads would each be pulling their data from the top of the queue and processing it. 您的每个线程都会从队列顶部提取数据并进行处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM