C# Class SocketServers.SpinLock

Represents a spin lock.

In software engineering, a spinlock is a lock where the thread simply waits in a loop ("spins") repeatedly checking until the lock becomes available. As the thread remains active but isn't performing a useful task, the use of such a lock is a kind of busy waiting. Once acquired, spinlocks will usually be held until they are explicitly released, although in some implementations they may be automatically released if the thread blocks (aka "goes to sleep").

Spinlocks are efficient if threads are only likely to be blocked for a short period of time, as they avoid the overhead of operating system process re-scheduling. For this reason, spinlocks are often used within operating system kernels. They are wasteful if the lock is held for a long period of time because they do not allow other threads to run while a thread is waiting for the lock to be released. They are always inefficient if used on systems with only one processor, as no other thread would be able to make progress while the waiting thread spun.

Note: This is a value type so it works very efficiently when used as a field in a class. Avoid boxing this or you will lose thread safety!

On a single CPU system, the kernel function SwitchToThread is called, which causes the calling thread to yield execution to another thread that is ready to run on the current processor. The operating system selects the next thread to be executed. The yield of execution is in effect for up to one thread-scheduling time slice. After that, the operating system reschedules execution for the yielding thread. The rescheduling is determined by the priority of the yielding thread and the status of other threads that are available to run.

Unfortunately, the yield of execution using SwitchToThread is limited to the processor of the calling thread. The operating system will not switch execution to another processor, even if that processor is idle or is running a thread of lower priority. Therefore, on a multiple-CPU system Thread.SpinWait(int) is used.

Mostra file Open project: vf1/serversockets

Public Methods

Method Description
Enter ( ) : void

Acquires an exclusive lock.

Exit ( ) : void

Releases an exclusive lock.

Private Methods

Method Description
StallThread ( ) : void

Method Details

Enter() public method

Acquires an exclusive lock.
public Enter ( ) : void
return void

Exit() public method

Releases an exclusive lock.
public Exit ( ) : void
return void