内存锁定以确保共享数据可以被多个线程读取,但只能被一个线程写入? [英] Memory lock to ensure shared data can be read from by many threads, but only written to by one?
问题描述
我正在尝试编写一个C#程序,其中对照线程中的特定值 x 检查列表 A 中的值.我希望线程将它们的 x 值与列表中的每个值进行比较,如果找不到,我希望它们将其值 x 添加到 A .然后,线程将从其私有内存中的列表中获得新的 x ,并再次开始将其与 A 中的值进行比较.该程序的目的是使 A 成为唯一值列表,并在线程中包含列表的所有值.
I am trying to write a C# program where values in a list A are checked against a particular value x in a thread. I would like the threads to compare their x values to each of the ones in the list, and if it is not found, I would like them to add their value x to A. The thread will then get a new x from a list in it's private memory, and begin comparing it to the values in A again. The objective of this program is to make A a list of unique values, and contain all of the values of the lists in the threads.
我想知道C#是否具有某些本机读/写锁,该锁将允许从单个列表中读取尽可能多的线程,但是一旦开始写,我希望所有其他线程在尝试之前等待再次从列表中读取.
I'm wondering if C# has some native read/write lock that will allow as many threads to read from a single list as possible, but once one starts to write, I would like all of the other threads to wait before attempting to read from the list again.
还有,有没有一种方法可以确保多个线程不会同时尝试写入?如果2个以上的线程包含相同的 x 值并尝试同时获取写锁,然后将相同的值一个接一个地添加到列表中,我会看到一个问题.
Also, is there a way I could ensure multiple threads won't attempt to write at the same time? I could see this being an issue if 2+ threads contained the same x value and tried to gain the write lock simultaneously - then added the same value to the list one after another.
推荐答案
我想知道C#是否具有某些本机读/写锁,该锁将允许从单个列表中读取尽可能多的线程
I'm wondering if C# has some native read/write lock that will allow as many threads to read from a single list as possible
是,请使用读取器写入器锁.这就是它的设计目的.
Yes, use a Reader Writer Lock. That's what it's designed for.
.net ReaderWriterLock
和ReaderWriterLockSlim
中分别有两个版本的ReaderWriterLock.后者是首选,因为它很有效.
There are two versions of ReaderWriterLock in .net ReaderWriterLock
and ReaderWriterLockSlim
respectively. Latter one is preferred as it is efficient.
这篇关于内存锁定以确保共享数据可以被多个线程读取,但只能被一个线程写入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!