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 / user-2029077

Minimus Heximus's questions

Martin Hope
Minimus Heximus
Asked: 2024-12-03 13:54:43 +0800 CST

Uma classe Integer segura para threads em C#

  • 9

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 respostas
  • 47 Views
Martin Hope
Minimus Heximus
Asked: 2024-11-29 22:17:13 +0800 CST

Por que a saída deste programa multithread varia a menos que Thread.Join seja usado ou Thread.Sleep seja removido?

  • 5

Tenho o seguinte programa, onde gero 1000 threads para incrementar uma variável compartilhada a e então faço cada thread dormir por 1 segundo:

using System;
using System.Diagnostics;
using System.Diagnostics.Metrics;
using System.Runtime.CompilerServices;
using System.Threading;

class Program
{

    static volatile int a = 0;
    static void Main()
    {
        List<Thread> threads = new List<Thread>();
        for (int i = 0; i < 1000; i++)
        {
            var t = new Thread(() =>
            {
                a++;
                Thread.Sleep(1000);
            });
            t.Start();
            threads.Add(t);
        }
        // foreach(Thread t in threads) t.Join();
        Thread.Sleep(60000);
        Console.WriteLine(a);
        Console.ReadKey();
    }
}

Problema:

Quando executo este código com a linha Thread.Sleep(1000) incluída e t.Join() comentado, a saída de Console.WriteLine(a) é menor que 1000, mesmo que eu aguarde 60 segundos para que os threads terminem.

Se eu descomentar o loop t.Join() ou comentar a linha Thread.Sleep(1000), a saída será consistentemente 1000.

Questões:

Por que a saída varia quando Thread.Sleep(1000) está presente e t.Join() está comentado?

Por que a saída se torna consistente (sempre 1000) quando t.Join() é usado ou Thread.Sleep(1000) é removido?

Eu apreciaria uma explicação do que está acontecendo aqui em termos de comportamento de thread e sincronização. Obrigado!

c#
  • 2 respostas
  • 64 Views

Sidebar

Stats

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

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

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

    • 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

    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
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +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

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