简体   繁体   中英

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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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