开发者

Why threads give different number on my program using ThreadPool?

开发者 https://www.devze.com 2023-02-22 14:51 出处:网络
why Number has different value? Thx class Program { static DateTime dt1; static DateTime dt2; static Int64 number = 0;

why Number has different value?

Thx

class Program
{
    static DateTime dt1;
    static DateTime dt2;
    static Int64 number = 0;
    public static void Main()
    {
        dt1 = DateTime.Now;

        for (int i = 0; i < 10; i++)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(WorkThread), DateTime.Now);
        }


        dt2 = DateTime.Now;
        Console.WriteLine("***");
        Console.ReadLine();
    }

    public static void WorkThread(object queuedAt)
    {
        number = 0;
        for (Int64 i = 0; i < 2000000; i++)
        {
            number += i;
        }
    开发者_开发问答    Console.WriteLine("number is:{0} and time:{1}",number,DateTime.Now - dt1);
    }
}


number is being shared between all of your threads, and you're not doing anything to synchronize access to it from each thread. So one thread might not have even started it's i loop (it may or may not have reset number to 0 at this point), while another can be half way through, and another might have finished it's loop completely and be at the Console.WriteLine part.


Here you have 10 threads acting on the static variable number at indeterminate times. One thread could on its 10000 iteration while another could just be beginning execution. And your routine begins by resetting number to 0. This logic would produce interesting results but nothing predictable.


If multiple threads access the same variable all at once, there is a risk of race conditions. A race condition is basically when the operations of the two threads are interwoven such that they interfere with eachother. To add a value to "number", the old value must be read, the sum computed, and the new value set. If those steps are being done by many threads at the same time, the value-setting can overwrite work done by previous threads, and the final result can change. You must use a lock (also called a critical section, mutex, or monitor) to protect the variable so this can't happen.

0

精彩评论

暂无评论...
验证码 换一张
取 消