Memory lock to ensure shared data can be read from

2020-04-12 15:41发布

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条回答
乱世女痞
2楼-- · 2020-04-12 16:38

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.

查看更多
登录 后发表回答