当前位置:网站首页>Multithreaded application (thread pool, singleton mode)
Multithreaded application (thread pool, singleton mode)
2022-07-07 11:07:00 【Exy-】
Thread pool
A bunch of threads handle tasks , It is mainly aimed at scenarios that need to be handled by a large number of tasks , Using multiple execution streams can improve processing efficiency
If a task arrives, create a thread to handle it, which has great disadvantages :
- cost : Total time = Thread creation time + Task processing time + Thread destruction time , If the task processing time is short , Then a lot of time is consumed by thread creation and destruction
- risk : If a large number of threads come in , The system may collapse under peak pressure
thought : Thread pool is actually a pile of created threads and a task queue , When a task comes, it is thrown into the thread pool , Allocate a thread to process
There is a maximum number of threads and task nodes in the thread pool , Avoid resource consumption .
Realization :
typedef void (*handler_t)(int data);
class ThreadTask{
private:
int _data;// Data to process
handler_t _handler;// Functions that process data
public:
ThreadTask() {}
ThreadTask(int data, handler_t handler):_data(data),
_handler(handler){}
void Run(){
_handler(_data);
}
};
class BlockQueue
{
private:
std::queue<ThreadTask> _queue;
int _capacity;
pthread_mutex_t _mutex;
pthread_cond_t _cond_pro;
pthread_cond_t _cond_con;
public:
BlockQueue(int maxq = MAXQ):_capacity(maxq){
pthread_mutex_init(&_mutex, NULL);
pthread_cond_init(&_cond_pro, NULL);
pthread_cond_init(&_cond_con, NULL);
}
~BlockQueue() {
pthread_mutex_destroy(&_mutex);
pthread_cond_destroy(&_cond_pro);
pthread_cond_destroy(&_cond_con);
}
bool Push(const ThreadTask &data){
pthread_mutex_lock(&_mutex);
while(_queue.size() == _capacity) {
pthread_cond_wait(&_cond_pro, &_mutex);
}
_queue.push(data);
pthread_mutex_unlock(&_mutex);
pthread_cond_signal(&_cond_con);
return true;
}
bool Pop(ThreadTask *data) {
pthread_mutex_lock(&_mutex);
while(_queue.empty() == true) {
pthread_cond_wait(&_cond_con, &_mutex);
}
*data = _queue.front();
_queue.pop();
pthread_mutex_unlock(&_mutex);
pthread_cond_signal(&_cond_pro);
return true;
}
};
class Threadpool{
private:
int _max_thread;// Maximum number of threads
int _max_queue;// The maximum number of nodes in the task queue
BlockQueue _queue;
public:
Threadpool(int max_thr=MAX_THREAD, int max_q=MAXQ):
_max_thread(max_thr),
_max_queue(max_q), _queue(max_q){
pthread_t tid;
int ret;
for (int i = 0; i < max_thr; i++) {
ret = pthread_create(&tid, NULL, thr_entry, this);
if (ret != 0) {
printf("thread create error\n");
exit(-1);
}
pthread_detach(tid);
}
}
static void *thr_entry(void *arg){
Threadpool *pool = (Threadpool*)arg;
while(1) {
ThreadTask task;
pool->_queue.Pop(&task);
task.Run();
}
}
bool TaskPush(const ThreadTask &task) {
_queue.Push(task);
}
};
The singleton pattern
Aimed at the scene : A class can only instantiate one object , Provide an access interface , In other words, a resource can only have one copy in memory
Purpose : To save memory ; Prevent data ambiguity ;
Concrete realization
Hungry and lazy mode
All hungry resources are loaded in advance and initialized , Use it directly when you use it ( Space for time )
- Constructor privatization , Cannot instantiate object outside class
- Instantiate globally unique objects within classes , Resources are shared separately , Pre run initialization , The initialization process does not consider thread safety issues
lazy : Load when resources are used ( It's used a lot )
- Constructor private
- Lock the access interface to protect the resource initialization loading process
- Second test , Prevent lock conflicts , Increase of efficiency
- Prevent the compiler from over Optimizing , Use volatile Modify pointer member variables
// Starving model
class Singleton
{
public:
static Singleton* GetInstance()
{
return &_instance;
}
private:
Singleton(){};
Singleton(Singleton const&);
static Singleton _instance;// Global unique object
};
// The sluggard model
class Singleton
{
public:
volatile static Singleton* GetInstance()
{
if (_instance == nullptr)
{
m_mutex.lock();
if (_instance == nullptr)
{
_instance = new Singleton();
}
m_mutex.unlock();
}
return _instance;
}
private:
Singleton() {};// Constructor private
volatile static Singleton* _instance;// Singleton object pointer
static mutex m_mutex;// The mutex
};
边栏推荐
- Bookmarking - common website navigation for programmers
- Static semantic check of clang tidy in cicd
- Shardingsphere sub database and table examples (logical table, real table, binding table, broadcast table, single table)
- 请问申购新股哪个证券公司开户是最好最安全的
- uniapp 在onLaunch中跳转页面后,点击事件失效解决方法
- How to play video on unityui
- Wallhaven wallpaper desktop version
- Laya common script commands
- 2022.7.5DAY597
- Get pictures through opencv, change channels and save them
猜你喜欢
How much review time does it usually take to take the intermediate soft exam?
China Southern Airlines pa3.1
[recommendation system 01] rechub
中级软件评测师考什么
When do you usually get grades in the soft exam? Online pedaling?
[untitled]
[pro test feasible] error while loading shared libraries solution
2022年7月10日“五心公益”活动通知+报名入口(二维码)
2021 summary and 2022 outlook
如何顺利通过下半年的高级系统架构设计师?
随机推荐
Vscode 尝试在目标目录创建文件时发生一个错误:拒绝访问【已解决】
P2788 math 1 - addition and subtraction
What is an intermediate network engineer? What is the main test and what is the use?
How to get hardware information in unity
在线硬核工具
The sixth training assignment
VR development optimization
How to prepare for the advanced soft test (network planning designer)?
Deep understanding of Apache Hudi asynchronous indexing mechanism
1324: [example 6.6] integer interval
简单易修改的弹框组件
一些线上学术报告网站与机器学习视频
Which securities company is the best and safest to open an account for the subscription of new shares
Unable to open kernel device '\.\vmcidev\vmx': operation completed successfully. Reboot after installing vmware workstation? Module "devicepoweron" failed to start. Failed to start the virtual machine
【OneNote】无法连接到网络,无法同步问题
【pyqt】tableWidget里的cellWidget使用信号与槽机制
How to play video on unityui
Is the gold content of intermediate e-commerce division in the soft exam high?
Unity websocket client
【推薦系統 01】Rechub