先看代码:

                 //设置可以同时处于活动状态的线程池的请求数目。 
                bool pool = ThreadPool.SetMaxThreads(8, 8);
                if (pool) {
                    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("参数1"));
                    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("参数2"));
                    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("参数3"));
                    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("参数4"));
                    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("参数5"));
                    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("参数6"));
                    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("参数7"));
                    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("参数8"));
                    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("参数9"));
                    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("参数10"));
                    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("参数11"));
                };

上面代码先设置线程池中最大并发量为8个,然后通过QueueUserWorkItem向线程池中添加11个方法,运行,输出结果:

可以看出,先运行了8个,当有一个任务结束后线程池中有空闲线程时,排队的下一个任务才会执行,

把最大并发量改成9试试:

{
                //设置可以同时处于活动状态的线程池的请求数目。 
                bool pool = ThreadPool.SetMaxThreads(9, 9);
                if (pool) {
                    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("参数1"));
                    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("参数2"));
                    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("参数3"));
                    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("参数4"));
                    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("参数5"));
                    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("参数6"));
                    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("参数7"));
                    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("参数8"));
                    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("参数9"));
                    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("参数10"));
                    ThreadPool.QueueUserWorkItem(o => this.DoSomethingLong("参数11"));
                };
               
            }

运行结果:

果然没错,这次是先执行9个,当有空闲线程时再执行下一个

 

总结一下

QueueUserWorkItem:将方法排入队列以便执行。 此方法在有线程池线程变得可用时执行。

 

GitHub 加速计划 / th / ThreadPool
8
0
下载
A simple C++11 Thread Pool implementation
最近提交(Master分支:3 个月前 )
9a42ec13 - 11 年前
fcc91415 - 11 年前
Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐