Skip to content

C# 如何修改使线程变的安全?

🏷️ C#

创建 20 个线程,每个线程计数 5w,合计应该计数 100w。

示例代码:

cs
using System;
using System.Threading;

namespace NotThreadSafeSample
{
    class Program
    {
        static void Main(string args)
        {
            int numThreads = 20;
            SharedState state = new SharedState();
            Thread threads = new Thread[numThreads];
            // 创建 20 个线程执行任务,每个任务把 State 加 5w,预想结果 100w
            for (int i = 0; i < numThreads; i++)
            {
                threads = new Thread(new Task(state).DoTheTask);
                threads.Start();
            }
            for (int i = 0; i < numThreads; i++)
            {
                threads.Join();
            }
            Console.WriteLine("summarized {0}", state.State);
            Console.ReadLine();
        }
    }

    class SharedState
    {
        public int State { get; set; }
    }

    class Task
    {
        private SharedState sharedState;

        public Task(SharedState sharedState)
        {
            this.sharedState = sharedState;
        }

        public void DoTheTask()
        {
            for (int i = 0; i < 50000; i++)
            {
                sharedState.State += 1;
            }
        }
    }
}

实际的多次执行结果:

summarized 335745
summarized 331077
summarized 327516
summarized 324865
summarized 367488
summarized 329521

离预想的结果 100w 相差甚远,而且每次执行的结果均不相同。

如何修改使线程变的安全,正确的计算出 100w 的结果?


点击查看答案

答案:只要在 Taskfor 循环里对 sharedState 加个 lock 就可以了。