开发者

ReaderWriteLockSlim or Lock

I m using ConcurrentBag to store object in run time. At some point I need to empty the bag and store the bag content to a list. This is what i do:

        IList<T> list = new开发者_如何学Python List<T>();

        lock (bag)
        {
            T pixel;

            while (bag.TryTake(out pixel))
            {
                list.Add(pixel);
            }
        }

My Question is with synchronization, As far as I read in the book lock is faster than others synchronization methods. Source -- http://www.albahari.com/threading/part2.aspx.

Performance is my second concern, I d like to know if I can use ReaderWriterLockSlim at this point. What would be the benefit of using ReaderWriterLockSlim? The reason is that, I dont want this operation to block incoming requests.

If yes, Should I use Upgradable Lock?

Any ideas ? Comments?


I'm not sure why you're using the lock. The whole idea behind ConcurrentBag is that it's concurrent.

Unless you're just trying to prevent some other thread from taking things or adding things to the bag while you're emptying it.

Re-reading your question, I'm pretty sure you don't want to synchronize access here at all. ConcurrentBag allows multiple threads to Take and Add, without you having to do any explicit synchronization.

If you lock the bag, then no other thread can add or remove things while your code is running. Assuming, of course, that you protect every other access to the bag with a lock. And once you do that, you've completely defeated the purpose of having a lock-free concurrent data structure. Your data structure has become a poorly-performing list that's controlled by a lock.

Same thing if you use a reader-writer lock. You'd have to synchronize every access.

You don't need to add any explicit synchronization in this case. Ditch the lock.


Lock is great when threads will do a lot of operations in a row(bursty - low contention)

RWSlim is great when you have a lot more read locks than write locks(read heavy - high read contention)

Lockless is great when you need a multiple readers and/or writers all working at the same time(mix of read/write - lots of contention)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜