[英]Memory lock to ensure shared data can be read from by many threads, but only written to by one?
I am trying to write a C# program where values in a list A are checked against a particular value x in a thread.我正在尝试编写一个 C# 程序,其中根据线程中的特定值x检查列表A中的值。 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 .
我希望线程将它们的x值与列表中的每个值进行比较,如果没有找到,我希望它们将它们的值x添加到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.
然后线程将从它的私有内存中的列表中获取一个新的x ,并再次开始将它与A 中的值进行比较。 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.
该程序的目标是使A成为一个唯一值列表,并包含线程中列表的所有值。
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.我想知道 C# 是否有一些本机读/写锁,允许尽可能多的线程从单个列表中读取,但是一旦开始写入,我希望所有其他线程在尝试读取之前等待再次列出清单。
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.
如果 2+ 个线程包含相同的x值并尝试同时获得写锁,我可以看到这是一个问题 - 然后一个接一个地将相同的值添加到列表中。
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
我想知道 C# 是否有一些本机读/写锁,允许尽可能多的线程从单个列表中读取
Yes, use a Reader Writer Lock .是的,使用Reader Writer Lock 。 That's what it's designed for.
这就是它的设计目的。
There are two versions of ReaderWriterLock in .net ReaderWriterLock
and ReaderWriterLockSlim
respectively. .net
ReaderWriterLock
和ReaderWriterLockSlim
有两个版本的 ReaderWriterLock。 Latter one is preferred as it is efficient.后一种是首选,因为它是有效的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.