基于ID字段的并发对象锁 [英] Concurrent object locks based on ID field

查看:71
本文介绍了基于ID字段的并发对象锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个生产者/消费者过程.消耗的对象具有一个ID属性(类型为整数),我希望一次仅消耗一个具有相同ID的对象.我该如何执行呢?

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 ?

也许我可以做这样的事情,但是我不喜欢它(创建的对象太多,而每天只能消耗一个或两个具有相同ID的对象,并且锁(_lockers)有点耗时:

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:同样的问题,ID属性为字符串类型(在这种情况下,cas可以锁定字符串.Internal(currentObject.ID)

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

推荐答案

如注释中所示,一种方法是拥有一个固定的锁池(例如32),并使用ID为32的模数来确定采用哪个锁. .这将导致一些错误的锁共享. 32是从空中挑选的数字-这取决于您分配的ID值,有多少消费者等.

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.

这篇关于基于ID字段的并发对象锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆