1

I have just started learning "Threading in C#". I found in a book that Thread.Sleep(0) relinquishes the thread’s current time slice immediately, voluntarily handing over the CPU to other threads.

When I wrote few lines of code to test it. I did not get the expected result. Here the the code I wrote.

class Program
{
    static void Main(string[] args)
    {
        Thread.CurrentThread.Name = "Thread A(main thread)";

        Thread thread = new Thread(PrintNumber);
        thread.Name = "Thread B";
        thread.Start();

        for (int i = 0; i < 40; i++)
        {
            Console.WriteLine("{0} | i = {1}", Thread.CurrentThread.Name, i);
        }
    }

    void PrintNumber()
    {
        for (int i = 0; i < 40; i++)
        {
            Console.WriteLine("{0} | i = {1}", Thread.CurrentThread.Name, i);

            if (i == 4)
            {
                Thread.Sleep(0);
            }
        }
    }
}

According to my understanding this will print up to 4 in thread B then it will resume the thread A. Next thread schedule is unpredictable. But this is not happening. While it comes to thread B for the first time sometimes it prints upto 6 sometimes 8 means totally unpredictable.

So is my concept of Theread.Sleep(0) is wrong? Can someone please clarify the concept

4

2 回答 2

3

如果它确实释放了线程的切片,那并不意味着您可以预测它的去向——它可以进入计算机上的任何进程。特别是,假设您有一台多核机器,则另一个线程可能完全由另一个内核提供服务。在如图所示的代码中,也有可能直到' 循环附近"Thread B"开始。Main启动线程不是即时的。

对您有用的场景很少Thread.Sleep(0),所有这些场景都涉及线程和内存模型的广泛知识。

于 2013-11-08T07:48:53.570 回答
2

Thread.Yield()确保下一个正在执行的线程不是当前线程。

于 2013-11-08T07:58:42.210 回答