Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concurrent object locks based on ID field

Tags:

c#

locking

I have a producer/consumer process. The consumed object has an ID property (of type integer), I want only one object with the same ID to be consumed at a time. How can I perform this ?

Maybe I can do something like this, but I don't like it (too many objects created while only one or two with the same ID a day can be consumed and the lock(_lockers) is a bit time consuming :

    private readonly Dictionary<int,object> _lockers = new Dictionary<int,object>();
    private object GetLocker(int id)
    {
        lock(_lockers)
        {
            if(!_lockers.ContainsKey(id))
                _lockers.Add(id,new object());
            return _lockers[id];
        }
    }



    private void Consume(T notif)
    {
            lock(GetLocker(notif.ID))
           {
            ...
           }
    }

enter code here

NB : Same question with the ID property being of type string (in that cas maybe I can lock over the string.Internal(currentObject.ID)

like image 643
Toto Avatar asked Dec 09 '09 10:12

Toto


People also ask

What does lock () return when a the lock is being held?

The lock statement acquires the mutual-exclusion lock for a given object, executes a statement block, and then releases the lock. While a lock is held, the thread that holds the lock can again acquire and release the lock. Any other thread is blocked from acquiring the lock and waits until the lock is released.

Is lock thread safe C#?

The lock statement is one of the simplest and most common tools for C# developers writing multithreaded applications. It can be used to synchronize access to blocks of code, achieving thread safety by allowing only one thread at a time to execute the code in that block.

How do you lock a method in C#?

The lock keyword makes it possible to block a section of code while working with another thread. To enter a section of code where an existing thread already exists, the other thread must wait until the previous thread's execution completes. As soon as the current thread in the function completes, the lock is released.


2 Answers

Can you make your IDs to be unique for each object? If so, you could just apply a lock on the object itself.

like image 141
Konamiman Avatar answered Oct 06 '22 08:10

Konamiman


As indicated in comment, one approach would be to have a fixed pool of locks (say 32), and take the ID modulo 32 to determine which lock to take. This would result in some false sharing of locks. 32 is number picked from the air - it would depend on your distibution of ID values, how many consumers, etc.

like image 33
Damien_The_Unbeliever Avatar answered Oct 06 '22 07:10

Damien_The_Unbeliever