SpinWait.Reset 메서드
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
스핀 카운터를 다시 설정합니다.
public:
void Reset();
public void Reset();
member this.Reset : unit -> unit
Public Sub Reset ()
예제
다음은 간단한 잠금 없는 스택 구현에서 SpinWait을 사용하는 예제입니다. (이것은 단지 예일 뿐입니다. 스레드로부터 안전한 효율적인 스택이 필요한 경우 ConcurrentStack을 사용하는 것이 좋습니다.)
using System;
using System.Threading;
public class LockFreeStack<T>
{
private volatile Node m_head;
private class Node { public Node Next; public T Value; }
public void Push(T item)
{
var spin = new SpinWait();
Node node = new Node { Value = item }, head;
while (true)
{
head = m_head;
node.Next = head;
if (Interlocked.CompareExchange(ref m_head, node, head) == head) break;
spin.SpinOnce();
}
}
public bool TryPop(out T result)
{
result = default(T);
var spin = new SpinWait();
Node head;
while (true)
{
head = m_head;
if (head == null) return false;
if (Interlocked.CompareExchange(ref m_head, head.Next, head) == head)
{
result = head.Value;
return true;
}
spin.SpinOnce();
}
}
}
Imports System.Threading
Public Class LockFreeStack(Of T)
Private m_head As Node
Private Class Node
Public [Next] As Node
Public Value As T
End Class
Public Sub Push(ByVal item As T)
Dim spin As New SpinWait()
Dim head As Node, node As New Node With {.Value = item}
While True
Thread.MemoryBarrier()
head = m_head
node.Next = head
If Interlocked.CompareExchange(m_head, node, head) Is head Then Exit While
spin.SpinOnce()
End While
End Sub
Public Function TryPop(ByRef result As T) As Boolean
result = CType(Nothing, T)
Dim spin As New SpinWait()
Dim head As Node
While True
Thread.MemoryBarrier()
head = m_head
If head Is Nothing Then Return False
If Interlocked.CompareExchange(m_head, head.Next, head) Is head Then
result = head.Value
Return True
End If
spin.SpinOnce()
End While
End Function
End Class
설명
이렇게 하면 SpinOnceNextSpinWillYield 이 인스턴스에서 호출 SpinOnce 이 실행되지 않은 것처럼 동작합니다. 인스턴스를 SpinWait 여러 번 다시 사용하는 경우 너무 빨리 생성되지 않도록 다시 설정하는 것이 유용할 수 있습니다.