Потокобезопасный класс Integer в C#.C#

Место общения программистов C#
Ответить
Anonymous
 Потокобезопасный класс Integer в C#.

Сообщение Anonymous »

После моего предыдущего вопроса я попытался исправить код, но результат все равно не тот, который я ожидал. Я попытался определить потокобезопасное целое число:

Код: Выделить всё

using System;
using System.Threading;

public struct SInt
{
private int _value;

public SInt(int initialValue = 0)
{
_value = initialValue;
}

public int Value => Volatile.Read(ref _value); // Interlocked.CompareExchange(ref _value, 0, 0);

// Add a value
public int Add(int value) => Interlocked.Add(ref _value, value);

// Subtract a value
public int Subtract(int value) => Interlocked.Add(ref _value, -value);

// Multiply the value
public int Multiply(int value)
{
int initial, computed;
do
{
initial = Value;
computed = initial * value;
}
while (Interlocked.CompareExchange(ref _value, computed, initial) != initial);

return computed;
}

// Divide the value
public int Divide(int value)
{
if (value == 0)
throw new DivideByZeroException();

int initial, computed;
do
{
initial = Value;
computed = initial / value;
}
while (Interlocked.CompareExchange(ref _value, computed, initial) != initial);
return computed;
}

// Increment the value
public int Increment() => Interlocked.Increment(ref _value);

// Decrement the value
public int Decrement() => Interlocked.Decrement(ref _value);

// Overloaded operators
public static SInt operator +(SInt a, int b)
{
a.Add(b);
return a;
}

public static SInt operator -(SInt a, int b)
{
a.Subtract(b);
return a;
}

public static SInt operator *(SInt a, int b)
{
a.Multiply(b);
return a;
}

public static SInt operator /(SInt a, int b)
{
a.Divide(b);
return a;
}

public static SInt operator ++(SInt a)
{
a.Increment();
return a;
}

public static SInt operator --(SInt a)
{
a.Decrement();
return a;
}

// Equality operators
public static bool operator ==(SInt a, SInt b) => a.Value == b.Value;

public static bool operator !=(SInt a, SInt b) => a.Value != b.Value;

// Comparison operators
public static bool operator  a.Value < b.Value;
public static bool operator  a.Value (SInt a, SInt b) => a.Value > b.Value;
public static bool operator >=(SInt a, SInt b) => a.Value >= b.Value;

// Implicit conversion from int to SInt
public static implicit operator SInt(int value) => new SInt(value);

// Implicit conversion from SInt to int
public static implicit operator int(SInt sInt) => sInt.Value;

public override bool Equals(object? obj)
{
if (obj is SInt other)
{
return this == other;
}
return false;
}

public override int GetHashCode() => Value.GetHashCode();

public override string ToString() => Value.ToString();
}
Затем я переписал программу:

Код: Выделить всё

using System;
using System.Diagnostics;
using System.Threading;

class Program
{
static void Main(string[] args)
{
List threads = new List();
SInt s = 0;
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 0; i 
{
s++;
Thread.Sleep(1000);
});
t.Priority = ThreadPriority.Highest;
threads.Add(t);
t.Start();
}
foreach (var t in threads)
t.Join();
stopwatch.Stop();
Console.WriteLine($"Time: {stopwatch.ElapsedMilliseconds / 1000.0} Seconds");
Console.WriteLine(s);
Console.WriteLine(threads.Count(t =>  t.ThreadState == System.Threading.ThreadState.Stopped));
Console.ReadKey();
}
}
вывод на моем ноутбуке:

Код: Выделить всё

Time: 85.16 Seconds
989
1000
Я ожидаю, что 989 будет 1000.
Что случилось?

Подробнее здесь: https://stackoverflow.com/questions/792 ... in-c-sharp
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»