SpinLock in .net

SpinLock是結構體, 相似於monitor, 可是垃圾回收付出的代價更小, 若是須要用到大量的lock而且執行的時間很是短,就能夠利用SpinLock, 須要注意的是SpinLock既然是結構體,傳遞時會產生副本,所以老是經過Ref來傳遞。 ui


The SpinLock structure is a low-level, mutual-exclusion synchronization primitive that spins while it waits to acquire a lock. On multicore computers, when wait times are expected to be short and when contention is minimal, SpinLock can perform better than other kinds of locks. However, we recommend that you use SpinLock only when you determine by profiling that the System.Threading.Monitor method or the Interlocked methods are significantly slowing the performance of your program. this

SpinLock may yield the time slice of the thread even if it has not yet acquired the lock. It does this to avoid thread-priority inversion, and to enable the garbage collector to make progress. When you use a SpinLock, ensure that no thread can hold the lock for more than a very brief time span, and that no thread can block while it holds the lock. spa

Because SpinLock is a value type, you must explicitly pass it by reference if you intend the two copies to refer to the same lock. debug

For more information about how to use this type, see System.Threading.SpinLock. For an example, see How to: Use SpinLock for Low-Level Synchronization. orm

SpinLock supports a thread-tracking mode that you can use during the development phase to help track the thread that is holding the lock at a specific time. Thread-tracking mode is very useful for debugging, but we recommend that you turn it off in the release version of your program because it may slow performance. For more information, see How to: Enable Thread-Tracking Mode in SpinLock. ci

相關文章
相關標籤/搜索