简体   繁体   中英

Lock free hash table for c#

Does anyone know of an implementation of a lock free hash table in C#? Or can anyone confirm for a fact that at least reads on a HashTable are thread-safe?

Edit:

I can read the documentation, but it's unclear.

"It is thread safe for multi-thread use when only one of the threads perform write (update) operations."

So, the question is, if I have multiple threads, and they all could write to the hashtable, I would use the writerlock. However, those same threads also read from the hashtable. Do I need a readerlock on the reads?

在修改集合之前,读取是线程安全的。

I can now answer the first part of this question:

Does anyone know of an implementation of a lock free hash table in C#?

Having just released an alpha version of one:

https://github.com/hackcraft/HackCraft.LockFree

I have one at https://bitbucket.org/JonHanna/ariadne and https://github.com/hackcraft/Ariadne

From the documentation :

Hashtable is thread safe for use by multiple reader threads and a single writing thread. It is thread safe for multi-thread use when only one of the threads perform write (update) operations, which allows for lock-free reads provided that the writers are serialized to the Hashtable. To support multiple writers all operations on the Hashtable must be done through the wrapper returned by the Synchronized method, provided that there are no threads reading the Hashtable object.

Enumerating through a collection is intrinsically not a thread safe procedure. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

此外,.NET 4.0正在向System.Collections.Concurrent命名空间添加ConcurrentDictionary ...

You can write your own Lock free hashtable by creating a new one and swapping it every time you modify it - it works well if you don't modify it often. (because it's extremely cheap to read and very expensive to write).

Otherwise, I would recommend using a ReaderWriterLockSlim (assuming you read more than you write) or a Monitor (lock statement) if you write a lot.

Orion说,您可能希望将哈希表与ReaderWriterLock结合使用。

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