• C# 多线程 整数 +1


     多线程 整数 +1; 有如下的写法:

    while (true)
    { 
        var mre = new AutoResetEvent(true);
        int m = 0;
    
        for (int i = 0; i < 200; i++)
        {
            Task.Run(() =>
            {
                mre.WaitOne();
                m++;
                mre.Set();
            });
        }
    
        Console.ReadLine();
        Console.WriteLine($"waiting...{m}");
    }
    
    
    while (true)
    {
        var mut = new Mutex();
    
        int m = 0;
    
        for (int i = 0; i < 200; i++)
        {
            _ = Task.Run(() =>
            {
                mut.WaitOne();
                m++;
               
                mut.ReleaseMutex();
                
            });
        }
        Console.ReadLine();
        Console.WriteLine($"waiting,mutex...{m}");
    }
    
    
    while (true)
    {
        SpinLock spinLock = new SpinLock(false);
        
        int m = 0;
    
        for (int i = 0; i < 200; i++)
        {
            bool sp = false;
            _ = Task.Run(() =>
            {
                try
                {
                    spinLock.Enter(ref sp);
                    m++;
                }
                catch (global::System.Exception e)
                {
                    global::System.Console.WriteLine(e.Message);
                }
    
                finally 
                {
                    if (sp)
                        spinLock.Exit();
                }
            });
        }
        Console.ReadLine();
        Console.WriteLine($"waiting...{m}");
    }
    
    
    while (true)
    {
        int m = 0;
    
        for (int i = 0; i < 200; i++)
        {
            Task.Run(() => {
                Interlocked.Increment(ref m);
            });
        }
        Console.ReadLine();
        Console.WriteLine($"waiting...{m}");
    }
    
    
    
    while (true) // 不正确
    {
        int m = 0;
    
        for (int i = 0; i < 200; i++)
        {
            Task.Run(() => {
                m++;
            });
        }
    
        Console.ReadLine();
        Console.WriteLine($"waiting...{m}");
    }
  • 相关阅读:
    连接mysql遇到的问题
    洛谷 P3369 【模板】普通平衡树(Treap/SBT)
    开博啦
    luogu【P2753】[USACO4.3]字母游戏Letter Game
    luogu【P3377】 【模板】左偏树
    POJ-2251
    HDU-1518
    Coderforces-455A
    UVA-1608
    Coderfocers-551C
  • 原文地址:https://www.cnblogs.com/qgbo/p/16375052.html
Copyright © 2020-2023  润新知