using System;
using System.Threading;
namespace Preparation.Utility
{
//其对应属性不应当有set访问器,避免不安全的=赋值
public class AtomicBool
{
private int v;//v==0为false,v==1为true
public AtomicBool(bool x)
{
v = x ? 1 : 0;
}
public override string ToString() => (Interlocked.CompareExchange(ref v, -2, -2) == 0) ? "false" : "true";
public bool Get() => (Interlocked.CompareExchange(ref v, -1, -1) != 0);
public static implicit operator bool(AtomicBool abool) => (Interlocked.CompareExchange(ref abool.v, -1, -1) != 0);
/// 返回操作前的值
public bool SetReturnOri(bool value) => (Interlocked.Exchange(ref v, value ? 1 : 0) != 0);
/// 赋值前的值是否与将赋予的值不相同
public bool TrySet(bool value)
{
return (Interlocked.CompareExchange(ref v, value ? 1 : 0, value ? 0 : 1) ^ (value ? 1 : 0)) != 0;
}
public bool And(bool x) => Interlocked.And(ref v, x ? 1 : 0) != 0;
public bool Or(bool x) => Interlocked.Or(ref v, x ? 1 : 0) != 0;
}
}