需求:当线程池中的任务都完成时,打印“所有任务已完成”

代码:

                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"));
                };
    
                Console.WriteLine("所有任务已完成");

输出结果:

这样写明显是不行的,要想达到目的,需要用到ManualResetEvent

更改后的代码:

                bool pool = ThreadPool.SetMaxThreads(9, 9);
                ManualResetEvent mre = new ManualResetEvent(false);
                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");
                        mre.Set();
                    });

                };
                mre.WaitOne();
                Console.WriteLine("所有任务已完成");

输出结果:

好了,看输出结果,目的达到了

 

这里主要用到了ManualResetEvent类中的Set()和WaitOne()方法

Set(): 将事件状态设置为有信号,其他线程继续执行。

WaitOne():阻止当前线程,简单来说是等待,等待set()的信号,等有信号后放开当前线程,继续执行,

 

以上是个人理解总结,如有理解错误,请指出,共同进步

 

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

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐