什么是使用一个线程池的正确方法? [英] what's the proper way to use a ThreadPool?

查看:138
本文介绍了什么是使用一个线程池的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的线程池的工作方式的理解是正确的,其目的之一是限制可以在给定时间被创建一个进程中的工作线程的数量。例如,如果设置MaxThreads至5,然后调用QueueUserWorkItem 30次,30请求将作出的线程池,但只有那些请求5将由一个新的线程提供服务,而其他25请求将被添加到队列和服务的一个在作为以前的请求完整的和现有的线程变得可用的时间。



在下面的代码,但是,在调用Thread.sleep代码(-1)保证了DoSomething的()方法将永远不会返回,这意味着当前线程将永远不会成为提供给后续请求。



不过我的线程池的作品不可能是正确的方式认识的,因为如果它是正确的下面的代码将只打印数字0-4,而不是0-29。



能否有人请解释线程池是如何工作的,以及为什么下面的代码是不是做什么,我认为它应该做的事?

 静态无效DoSomething的(对象N)
{
Console.WriteLine(N);
Thread.sleep代码(-1);
}

静态无效的主要(字串[] args)
{
ThreadPool.SetMaxThreads(5,5);
表示(中间体X = 0; X小于30; X ++)
{
ThreadPool.QueueUserWorkItem(新WaitCallback(DoSomething的)中,x);
}
Console.Read();
}


解决方案

ThreadPool.SetMaxThreads(5,5)



表示活动线程的数量为5(如果你有超过5个CPU核心),不并不意味着线程池只能创建5个线程。
线程= CPU核心* 250。



Thread.sleep代码线程池的最大数量,线程是不活动的,所以它不会影响到其他的线程的执行。


If my understanding of the way the ThreadPool works is correct, one of its purposes is to limit the number of worker threads within a process that can be created at a given time. For example, if you set MaxThreads to 5 and then call QueueUserWorkItem 30 times, 30 requests will be made to the ThreadPool, but only 5 of those requests will be serviced by a new thread, while the other 25 requests will be added to the queue and serviced one at time as previous requests complete and existing threads becomes available.

In the code below, however, the call to Thread.Sleep(-1) guarantees that the DoSomething() method will never return, meaning that the current thread will never become available to subsequent requests.

But my understanding of the way a ThreadPool works cannot be correct, because if it were correct the code below would print only the numbers 0-4, rather than 0-29.

Can someone please explain how the ThreadPool works and why the below code isn't doing what I thought it should be doing?

    static void DoSomething(object n)
    {
        Console.WriteLine(n);
        Thread.Sleep(-1);
    }

    static void Main(string[] args)
    {
        ThreadPool.SetMaxThreads(5, 5);
        for (int x = 0; x < 30; x++)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(DoSomething), x);
        }
        Console.Read();
    }

解决方案

ThreadPool.SetMaxThreads(5, 5)

means the number of active thread is 5 (if you have more than 5 cpu core), does not mean that the ThreadPool can only create 5 threads. The ThreadPool maximum number of threads = CPU Core * 250.

After Thread.Sleep, the thread is inactive, so it will not affect the execution of other threads.

这篇关于什么是使用一个线程池的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆