SpinWait.Reset メソッド

定義

スピン カウンターをリセットします。

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

注釈

これにより、 への呼び出しNextSpinWillYieldがこのインスタンスに対してSpinOnce発行されていないかのように行SpinOnceわれ、動作します。 インスタンスが SpinWait 何度も再利用される場合は、すぐに生成されないようにリセットすると便利な場合があります。

適用対象

こちらもご覧ください