Memory lock to ensure shared data can be read from by many threads, but only written to by one?

烂漫一生 提交于 2020-04-07 05:38:18

问题


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.

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.

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.


回答1:


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.

There are two versions of ReaderWriterLock in .net ReaderWriterLock and ReaderWriterLockSlim respectively. Latter one is preferred as it is efficient.



来源:https://stackoverflow.com/questions/33846013/memory-lock-to-ensure-shared-data-can-be-read-from-by-many-threads-but-only-wri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!