AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 79246409
Accepted
Minimus Heximus
Minimus Heximus
Asked: 2024-12-03 13:54:43 +0800 CST2024-12-03 13:54:43 +0800 CST 2024-12-03 13:54:43 +0800 CST

Uma classe Integer segura para threads em C#

  • 772

Depois da minha pergunta anterior , tentei consertar o código, mas ainda assim a saída não é o que eu esperava. Tentei definir um inteiro thread safe:

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 <(SInt a, SInt b) => a.Value < b.Value;
    public static bool operator <=(SInt a, SInt b) => a.Value <= b.Value;
    public static bool operator >(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();
}

Então reescrevi o programa:

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

class Program
{
    static void Main(string[] args)
    {
        List<Thread> threads = new List<Thread>();
        SInt s = 0;
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();
        for (int i = 0; i <1000; i++)
        {
            var t = new Thread(() =>
            {
                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();
    }
}

saída no meu laptop:

Time: 85.16 Seconds
989
1000

Espero que 989 seja 1000.

O que está errado?

c#
  • 2 2 respostas
  • 47 Views

2 respostas

  • Voted
  1. Best Answer
    wohlstad
    2024-12-03T14:25:59+08:002024-12-03T14:25:59+08:00

    Em C# a structé um tipo de valor .

    Portanto, quando você o devolve, por exemplo:

    public static SInt operator ++(SInt a)
    {
        a.Increment();
        return a;   // <-- here a copy is returned
    }
    

    Você realmente devolve uma cópia.

    Se SIntfosse, classele se comportaria como você espera, porque sendo um tipo de referência, ele retornaria uma referência à instância atual.

    Nota:
    Como @user555045 comentou acima, mesmo que você resolva esse problema específico de uso operator++, você ainda terá problemas quando ele for usado em expressões mais complexas.

    • 1
  2. Theodor Zoulias
    2024-12-03T14:39:35+08:002024-12-03T14:39:35+08:00

    Além da resposta de wohlstad , gostaria de apontar uma falha na ++implementação:

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

    Esta operação não é atômica. O correto é:

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

    Dessa forma, você obteria um resultado correto de um código como:

    SInt x = s++;
    
    • 1

relate perguntas

  • Polly DecorrelatedJitterBackoffV2 - como calcular o tempo máximo necessário para concluir todas as novas tentativas?

  • Wpf. Role o DataGrid dentro do ScrollViewer

  • A pontuação que ganhei na página do jogo com .NET MAUI MVVM não é visível em outras páginas. Como posso manter os dados de pontuação no dispositivo local

  • Use a hierarquia TreeView com HierarchicalDataTemplate de dentro de um DataTemplate

  • Como posso melhorar essa interface de validação no .NET?

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Por que esse código Java simples e pequeno roda 30x mais rápido em todas as JVMs Graal, mas não em nenhuma JVM Oracle?

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Quando devo usar um std::inplace_vector em vez de um std::vector?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Marko Smith

    Estou tentando fazer o jogo pacman usando apenas o módulo Turtle Random e Math

    • 1 respostas
  • Martin Hope
    Aleksandr Dubinsky Por que a correspondência de padrões com o switch no InetAddress falha com 'não cobre todos os valores de entrada possíveis'? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge Por que esse código Java simples e pequeno roda 30x mais rápido em todas as JVMs Graal, mas não em nenhuma JVM Oracle? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer Quando devo usar um std::inplace_vector em vez de um std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB Por que o GCC gera código que executa condicionalmente uma implementação SIMD? 2024-02-17 06:17:14 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve