0

From what I'm reading, semaphores are designed to allow multiple threads to access a pool of resources at the same time. I'm also reading that mutexes only allow a single thread to access a resource a time. I'm currently working with some code that uses a SemaphoreSlim to ensure that only one thread can access a resource.

Would it ever make sense to create a semaphore, where only a single thread can access the pool of resources at once? In that case, why not use a Mutex? Or (from what I'm reading) a similar construct in C# - a lock or a Monitor? It sounds like mutexes/locks/monitors are simpler, and less potentially-misleading.

Sinatr
  • 20,892
  • 15
  • 90
  • 319
Daniel Neel
  • 1,197
  • 13
  • 28
  • `SemaphoreSlim` is waaay faster than `Mutex`, [rtfm](http://www.albahari.com/threading/part2.aspx#_Locking). – Sinatr Jan 29 '18 at 15:54
  • You would want to use `Monitor` most of times, but it has a limitation I can't remember right now, something with leaving in another thread. `SemaphoreSlim` doesn't have it. – Sinatr Jan 29 '18 at 16:07
  • @Sinatr isn't `Monitor` just `lock`? – FCin Jan 29 '18 at 16:11
  • @FCin, `lock` [is implemented](https://stackoverflow.com/a/4978936/1997232) using `Monitor`. – Sinatr Jan 29 '18 at 16:14
  • 1
    @Sinatr that is what I'm saying. `lock` is syntactic sugar for `Monitor`. – FCin Jan 29 '18 at 16:32
  • @Sinatr lock is compiled into a try/finally that _uses_ Monitor to achieve its functionality, it’s not “syntactic sugar for monitor” – Scott Perham Jan 29 '18 at 17:00
  • @ScottPerham The point I'm trying to make is that someone might think that using `Monitor` might be something new and rare when in reality it is created every time some uses `lock`. – FCin Jan 29 '18 at 19:19

1 Answers1

1

If single thread is granted an exclusive access to the resource, I don't see a reason why not use Mutex or any other type meant for exclusive lock.

It sounds like mutexes/locks/monitors are simpler, and less potentially-misleading.

Can't argue with that, in this case.

Tigran
  • 61,654
  • 8
  • 86
  • 123