当前位置:网站首页>Producer consumer model based on thread pool (including blocking queue)
Producer consumer model based on thread pool (including blocking queue)
2022-07-03 02:15:00 【abs(ln(1+NaN))】
5、 Thread execution function Routines
One 、 Thread pool
Same as memory pool , Thread pool is also to improve efficiency . A server may receive many requests in a short time , Wait for the request to be received before creating the thread , At this point, you need to create a thread , This will reduce the processing speed .

In response to this situation , We usually create a batch of threads in advance , Reduce the cost of creating and destroying threads in a short time . It's like going to a hot pot restaurant to eat hot pot , The store won't wait for you to come to the slaughterhouse to get the meat , I will definitely prepare the meat first .

Two 、 Model implementation
Now we are going to build such a model , As a producer, the main thread constantly adds tasks to the task queue , The threads in the thread pool are constantly getting tasks from the task queue . Suppose the capacity of the task queue is unlimited .

Just like blocking queues , The key to implementing such a model is still Put on the task PushTask and Take task PopTask, besides , When creating a thread , There is one detail that needs attention
1、 preparation

2、 Create thread
We create at one time 4 Threads , The parameters to be passed to the thread are tentative , For convenience , We don't actively recycle threads here , Instead, choose to separate threads .

What needs to be noted here is ,pthread_create The third argument to the function , The passed in function must meet
(1) The return value is void*
(2) There is only one input parameter , That's it void*

But actually ,Routines Is defined in the class , Is a member function , The parameter will contain a hidden this The pointer , So from the perspective of compiler, it becomes Routines(ThreadPool<T>* this , void* args), So we add... At the beginning of the function static
Member functions are generally placed in the code area , Member function added static in the future , At this time, it will be placed in the global area , At this time, the parameters are only void*, Will not contain hidden this The pointer
3、PushTask function
At this time, because the capacity of the task queue has no upper limit , So we don't need to consider the situation that the task queue is full ._task_queue It's a critical resource , We need to use mutexes to protect this critical resource
The initialization and destruction of mutexes are not shown here .

There is another step we need to wait for the implementation PopTask The function will be written later

4、PopTask function
When taking a task , It is necessary to consider the maintenance of critical resources , Also consider the situation that the task queue is empty .
(1) Since it is to maintain critical resources , Then you need to lock and unlock
(2) Considering whether the task queue is empty , When the task queue is empty , It means that the consumer thread cannot continue to fetch tasks , At this point, add the consumer thread to Wait in condition variable , When the producer thread joins the task , Then wake up the consumer thread .
Initialization and destruction of condition variables , It's not shown here .

PopTask The function is implemented as follows :

PushTask The complement of function :

5、 Thread execution function Routines
Now? Routines It is put into the global area , But threads in the thread pool need access Task queue , Therefore, we need to execute function transfer to the thread this The pointer , In this case , Each thread can access class member variables

Then we get this The pointer , Use a name that To receive this this The pointer

We can write an empty Task class , It looks like this

The complete code of the thread execution function is as follows :

3、 ... and 、 Model test
The main function of the test is as follows , The main thread acts as the producer thread every 1s Add a task to the task queue .

The effect shown here is similar to that of the previous blocking queue

边栏推荐
- [Yu Yue education] reference materials of chemical experiment safety knowledge of University of science and technology of China
- Exception handling in kotlin process
- Trial setup and use of idea GoLand development tool
- MySQL学习03
- 各国Web3现状与未来
- Wechat applet development tool post net:: err_ PROXY_ CONNECTION_ Failed agent problem
- Wechat applet Development Tool Post net:: Err Proxy Connexion Problèmes d'agent défectueux
- Return a tree structure data
- 微服务组件Sentinel (Hystrix)详细分析
- Servlet中数据传到JSP页面使用el表达式${}无法显示问题
猜你喜欢

Visualisation de l'ensemble de données au format yolov5 (fichier labelme json)

Technology sharing | Frida's powerful ability to realize hook functions

Introduce in detail how to communicate with Huawei cloud IOT through mqtt protocol

Solution for processing overtime orders (Overtime unpaid)

Comment communiquer avec Huawei Cloud IOT via le Protocole mqtt

How do it students find short-term internships? Which is better, short-term internship or long-term internship?

MySQL learning 03

Detailed introduction to the usage of Nacos configuration center

詳細些介紹如何通過MQTT協議和華為雲物聯網進行通信

Stm32f407 ------- IIC communication protocol
随机推荐
微信小程序开发工具 POST net::ERR_PROXY_CONNECTION_FAILED 代理问题
[shutter] hero animation (hero realizes radial animation | hero component createrecttween setting)
Kotlin middle process understanding and Practice (I)
Cfdiv2 fixed point guessing- (interval answer two points)
Introduce in detail how to communicate with Huawei cloud IOT through mqtt protocol
4. 类和对象
Flink CDC mongoDB 使用及Flink sql解析monggo中复杂嵌套JSON数据实现
Reprint some Qt development experience written by great Xia 6.5
[Yu Yue education] Jiujiang University material analysis and testing technology reference
8 free, HD, copyright free video material download websites are recommended
Swift开发学习
In 2022, 95% of the three most common misunderstandings in software testing were recruited. Are you that 5%?
[camera topic] complete analysis of camera dtsi
How to refresh the opening amount of Oracle ERP
Modify table structure
A 30-year-old software tester, who has been unemployed for 4 months, is confused and doesn't know what to do?
Anna: Beibei, can you draw?
Y54. Chapter III kubernetes from introduction to mastery -- ingress (27)
Use go language to realize try{}catch{}finally
MySQL learning 03