C++ 短时间高并发任务用即时多线程好还是线程池好?
阿神
阿神 2017-04-17 15:31:18
0
3
460

我用C++写了个本地代理服务器,目前使用的是即时创建,即时销毁的方式使用多线程的,每一个HTTP请求创建一个线程,交换数据的时候创建一个线程(即一个线程向客户端取数据向服务端发,一个线程向服务端取数据向客户端发),这些线程处理任务的时间都非常短,处理完后即CloseHandle销毁了。
但有时候并发请求数多了以后,感觉还是有点延迟。这种情况下,是不是采用线程池比较好?

阿神
阿神

闭关修行中......

reply all(3)
阿神

If your http request processing is time-consuming, then it is a good choice to create a thread for each http request.
But your current situation is that the time to process the task is very short, so most of the time is spent on creating and destroying threads.

You can use the thread pool to process the task queue.
You can refer to the implementation below.
C++11 simple thread pool code reading http://www.cnblogs.com/oloroso/p/5881863.html

伊谢尔伦

The overhead of thread creation and destruction is very high, and if there are too many threads, the memory usage will be very high. It is estimated that under the fourth generation i7 DDR5, only a thousand levels of creation and destruction can be completed per second. This overhead is configuration and platform dependent.

The thread pool implemented using std::condition_variable and std::mutex with the same configuration can easily complete millions of synchronizations per second.

You can write a simple program to test the specific time consumption. It is recommended to use a thread pool.

小葫芦

In order to prevent sudden requests, a thread pool needs to be used to allocate the number of threads in advance according to business requests. The operation of the thread pool is asynchronous, which greatly reduces the competition for thread resources.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template