Does using a lock have better performance than using a local (single application) semaphore?
I read this blog from msdn : Producer consumer solution on msdn
and I didn’t like their solution to the problem because there are always 20 elements left in the queue.
So instead, I thought about using a ‘Semaphore’ that will be available only in my app (I just won’t name it in the constructor), but I don’t know how it will effect the app’s performance.
Does anyone have an idea if it’ll affect the performance? What are the other considerations to use a lock and not ‘Semaphore’?
Lock(obj) is the same as Monitor.Enter(obj); A lock is basicaly an unary semaphore. If you have a number of instances of the same ressource (N) you use a semaphore with the initialization value N. A lock is mainly used to ensure that a code section is not executed by two threads at the same time.
So a lock can be implemented using a semaphore with initialization value of 1. I guess that Monitor.Enter is more performant here but I have no real information about that. A test will be of help here. Here is a SO thread that handels about performance.
For your problem a blocking queue would be the solution. (producer consumer) I suggest this very good SO thread.
Here is another good source of information about Reusable Parallel Data Structures.