本文介绍了Thread.sleep代码是否妨碍其他线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一个控制台程序想要10个线程分批启动,等待5秒钟,并停止在批处理。

 静态无效主要(字串[] args)
{
System.Threading.Tasks.Parallel.For(0,10,(指数)=>
{
动作< INT>行为=(I)=>
{
Console.Write(启动{0},我);
Thread.sleep代码(5000);
};

act.BeginInvoke(索引,OnTaskComplete,指数);
});

Console.ReadKey();
}

静态无效OnTaskComplete(IAsyncResult的RES)
{
Console.Write(说完{0},res.AsyncState);
}



但结果不出我所料,10个线程启动一个逐当注释掉Thread.sleep代码,所有线程开始和结束在一个慢(约1秒的时间间隔),甚至有些完成出来之前,一些启动。



闪光灯。



确实 Thread.sleep代码影响其他线程?反正有做一个纯粹的空闲时间?



/ ------------------------ -----编辑-----------------------------



同样的问题也发生在:

 静态无效的主要(字串[] args)
{
系统。 Threading.Tasks.Parallel.For(0,10,(指数)= GT;
{
Console.Write(开始{0},索引);
Thread.sleep代码(5000 );
Console.Write(fnish {0},指数);
});

Console.ReadKey();
}



---------------- ------编辑------------------------



终于让我找到一个可爱的方式替代了Thread.Sleep

 静态无效的主要(字串[] args)
{
系统.Threading.Tasks.Parallel.For(0,10,(指数)= GT;
{
Console.Write(开始{0},索引);

变种T1 =新System.Threading.Timer(新TimerCallback(MyTimerCallback),索引,5000,0);
});

Console.ReadKey();
}

静态无效MyTimerCallback(对象o)
{
Console.Write(计时器回呼);
}


解决方案

这是由设计。您所看到的线程池经理试图保持在执行状态的线程数量有限。重要的是要确保你的程序不运行多个线程比你的机器有CPU核心。这是低效的,当Windows被迫开始交换活动的线程之间的核心更少完成工作。线程池管理器是不够聪明,知道该线程处于休眠状态,而不是实际执行任何工作。



在一个双核的机器,你会看到第一2个线程开始的时候了。然后附加的线程被允许运行,逐一以一秒的间隔时,该活动线程没有取得任何进展和线程管理器通知很可能被阻止。其中线程都被释放并执行Console.Write()调用的顺序是不确定性的。



这是当然的人工测试,真正的线程不睡觉。如果您有块很长一段时间,等待I / O请求来完成,例如然后使用线程池线程(任务)的线程是不是最好的解决方案。


Here is a console program want 10 threads start in batch, wait 5 seconds, and stop in batch.

static void Main(string[] args)
{
    System.Threading.Tasks.Parallel.For(0, 10, (index) =>
    {
        Action<int> act = (i) =>
        {
            Console.Write("start {0} ", i);
            Thread.Sleep(5000);
        };

        act.BeginInvoke(index, OnTaskComplete, index);
    });

    Console.ReadKey();
}

static void OnTaskComplete(IAsyncResult res)
{
    Console.Write("finish {0} ", res.AsyncState);
}

but the result is not what I expected, 10 threads start one-by-one SLOWLY(around 1 second interval), even some "finish" comes out before some "start".

when comment out Thread.Sleep, all threads start and finish in flash.

Does Thread.Sleep affect other threads? Is there anyway to make a pure idle time?

/-----------------------------edit-----------------------------

same problem also happen in:

static void Main(string[] args)
{
    System.Threading.Tasks.Parallel.For(0, 10, (index) =>
    {
        Console.Write("start {0} ", index);
        Thread.Sleep(5000);
        Console.Write("fnish {0} ", index);
    });

    Console.ReadKey();
}

----------------------Edit------------------------

finally I found a lovely way to substitute thread.sleep

static void Main(string[] args)
{
    System.Threading.Tasks.Parallel.For(0, 10, (index) =>
    {
        Console.Write("start {0} ", index);

        var t1 = new System.Threading.Timer(new TimerCallback(MyTimerCallback), index, 5000, 0);
    });

    Console.ReadKey();
}

static void MyTimerCallback(object o)
{
    Console.Write("Timer callbacked ");
}
解决方案

This is by design. You are seeing the threadpool manager trying to keep a limited number of threads in the executing state. Important to ensure that your program isn't running more threads than your machine has cpu cores. That's inefficient, less work gets done when Windows is forced to start swapping the cores between active threads. The threadpool manager isn't smart enough to know that the thread is sleeping and not actually performing any work.

On a dual-core machine, you'll see the first 2 threads starting right away. Then additional threads are allowed to run, one by one with a one second interval when the thread manager notices that the active threads are not making any progress and are probably blocked. The order in which threads are released and execute the Console.Write() call is not deterministic.

This is an artificial test of course, real threads don't sleep. If you have threads that block for a long time, waiting for an I/O request to complete for example then using threadpool threads (tasks) is not the best solution.

这篇关于Thread.sleep代码是否妨碍其他线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 23:17
查看更多