using System.Threading;
namespace dotNetty_kcp.thread
{
public class AtomicBoolean
{
private int _value;
public AtomicBoolean()
: this(false) {
}
/// Creates a new AtomicBoolean instance with the initial value provided.
///
public AtomicBoolean(bool value) {
_value = value ? 1 : 0;
}
///
/// This method returns the current value.
///
///
/// The bool value to be accessed atomically.
///
public bool Get() {
return _value != 0;
}
///
/// This method sets the current value atomically.
///
///
/// The new value to set.
///
public void Set(bool value) {
Interlocked.Exchange(ref _value, value ? 1 : 0);
}
///
/// This method atomically sets the value and returns the original value.
///
///
/// The new value.
///
///
/// The value before setting to the new value.
///
public bool GetAndSet(bool value) {
return Interlocked.Exchange(ref _value, value ? 1 : 0) != 0;
}
///
/// Atomically sets the value to the given updated value if the current value == the expected value.
///
///
/// The value to compare against.
///
///
/// The value to set if the value is equal to the expected value.
///
///
/// true if the comparison and set was successful. A false indicates the comparison failed.
///
public bool CompareAndSet(bool expected, bool result) {
int e = expected ? 1 : 0;
int r = result ? 1 : 0;
return Interlocked.CompareExchange(ref _value, r, e) == e;
}
///
/// This operator allows an implicit cast from AtomicBoolean to int.
///
public static implicit operator bool(AtomicBoolean value) {
return value.Get();
}
}
}