Does lock, Monitor, Mutex waste CPU cycles like SpinWait?
Recently I started learning Parallel Programming using Task Parallel Library in C# and I read that SpinLock wastes CPU cycles and keeps spinning till the lock is acquired. Also while comparing methods: Thread.Sleep and Thread.SpinUntil I found that Thread.sleep releases scheduler so that scheduler can schedule other threads. Does this hold true for the lock, Monitor, Mutex, and Interlocked also?. Does CLR allow the scheduler to schedule other threads when lock, Monitor, Mutex, Interlocked are waiting to enter inside the critical section?
Hard to understand your question. I try it this way:
- SpinLock is special, because it does a "busy wait". Only to be used when you know that the thread would wait for a very short time, e.g. some CPU cycles.
- lock, Monitor and Mutex do not busy wait. These are the regular and most commonly used ways of thread synchronization.
- Interlocked doesn’t lock at all. It’s for so called "lock free synchronization", which is tricky and should rarely be used.
I don’t know what you mean by the scheduler. Threads are running until they are locked somehow. Only one thread can get the same lock. When you create your own threads, they are scheduled by the OS (AFAIK). When you used thread pools, they are scheduled there.