当前位置:网站首页>17.13 supplementary knowledge, thread pool discussion, quantity discussion and summary
17.13 supplementary knowledge, thread pool discussion, quantity discussion and summary
2022-06-26 17:49:00 【zzyzxb】
One : Add some knowledge
<1> spurious wakeup
class MA
{
public:
int i = 0;
std::unique_lock<std::mutex> rtn_unique_gurad()
{
std::unique_lock <std::mutex> tmpgurad(my_mutex_1);
return tmpgurad; // Returns a local... From the function unique_lock Objects are OK , The 14th session of Chapter 3 talked about mobile constructors
// Returning this local object will cause the system to generate temporary unique_lock object , And call unique_lock The move constructor for
}
// Take the message you've received ( Player orders ) Threads put into a queue
void inMsgRecvQueue()
{
for (int i = 0; i < 100000; ++i)
{
cout << "inMsgRecvQueue() perform , Insert an element : " << i << endl;
std::unique_lock<std::mutex> sbguard_1 = rtn_unique_gurad();
msgRecvQueue.push_back(i); // Suppose this number i That's the order we received , Directly into the message queue
// If outMsgRecvQueue() Processing a transaction , It will take a while , Instead of being stuck in wait() There waiting to wake up ;
// Now this notify_one() This call may not work .
my_cond.notify_one(); // We tried to wait() Thread wake up , Finish this line , that outMsgRecvQueue() Inside wait() Will be awakened
}
cout << "i = " << i << endl;
}
// Take the data of the thread from the queue
void outMsgRecvQueue()
{
int command = 0;
while (true)
{
//wait() To wait for something
// If the second parameter lambda The return value of the expression is true, that wait() Go straight back to ;
// If the second parameter lambda The return value of the expression is false, that wait() Will unlock mutex , And jam into the bank
// When will the jam stop ? Blocking some other thread to call notify_one() Member functions ;
// If wait() There is no second parameter :my_cond.wait(sbguard1); Then it's like the second parameter lambda Expression return false The effect is the same , Block the bank
//wait() Will unlock mutex , And block to the bank , Blocking to another thread to call Champions League notify_one() Member functions ;
// When other threads use notify_one() The book wait()( It was sleeping / Blocking ) After waking up ,wait I started to get back to work , After recovery wait What do you do ?
//a> wait() Constantly trying to regain the mutex lock , If not , Then the process is stuck in wait() It's here to get , If you get the lock ( It's like a lock ), that wait() Continue to implement b;
//b>
//b.1> If wait() There's a second parameter (lambda), Just judge this lambda expression , If lambda Expression for false, that wait() Unlock mutex again , Then sleep here and wait to be notify_one Wake up the ;
//b.2> If lambda Expression for true, be wait return , The process goes down ( At this point, the mutex is locked );
//b.3> If wait() There is no second parameter , be wait() return , The process goes down .
std::unique_lock<std::mutex> sbguard_1(my_mutex_1);
my_cond.wait(sbguard_1, [this] { // One lambda It's a callable object ( function )
if (!msgRecvQueue.empty())
return true;
return false;
});
// As long as the process can come here , This mutex must be locked , meanwhile msgRecvQueue At least one piece of data
command = msgRecvQueue.front();
msgRecvQueue.pop_front();
sbguard_1.unlock(); // because unique_lock The flexibility of the , So we can always unlock Unlock , So as not to lock for too long .
cout << "outMsgRecvQueue() perform , Take out an element " << command << " " << std::this_thread::get_id() << endl;
} //end while
cout << "end" << endl;
}
private:
list<int> msgRecvQueue; // Containers ( Message queue ), It is used to send commands on behalf of players
mutex my_mutex_1; // Created a mutex ( A lock )
std::condition_variable my_cond; // Generate a conditional variable object
};
int main()
{
MA myobj;
std::thread myOutMsgObj(&MA::outMsgRecvQueue, &myobj); // The second parameter is the reference , To ensure that the same object is used in the thread
std::thread myInMsgObj(&MA::inMsgRecvQueue, &myobj);
myOutMsgObj.join();
myInMsgObj.join();
cout << "main End of main function execution " << endl; // Finally, execute this sentence , The whole process exits
return 0;
}
spurious wakeup :wait There must be a second parameter in the (lambda) And this lambda It is necessary to correctly judge whether the public data to be processed exists ;
wait()、notify_one()、notify_all().
<2>atomic
class MA
{
public:
MA()
{
atm = 0;
}
public:
void inMsgRecv()
{
for (int i = 0; i < 10000000; ++i)
{
//atm += 1;
atm = atm + 1; // read atm It's an atomic operation , But the whole line of code is not an atomic operation
//auto atm2 = atm; // Initialization is not allowed during this definition , Show “ An attempt was made to reference a deleted function ” The compiler must have killed the copy constructor =delete, Because the compiler is not easy to operate
//atomic<int> atm2 = atm; // Not allowed
//atomic<int> atm2;
//atm2 = atm // An attempt was made to reference a deleted function , Copy assignment operators are also not allowed
//load(): Read atomically atomic The value of the object
atomic<int> atm2(atm.load()); // read
auto atm3(atm.load());
//store() Write content atomically
atm2.store(12);
atm2 = 12;
}
}
void outMsgRecv()
{
int command = 0;
while (true)
{
cout << "atm = " << atm << endl;
} //end while
cout << "end" << endl;
}
private:
atomic<int> atm;
};
int main()
{
MA myobj;
std::thread myOutMsgObj(&MA::outMsgRecv, &myobj); // The second parameter is the reference , To ensure that the same object is used in the thread
std::thread myInMsgObj(&MA::inMsgRecv, &myobj);
std::thread myInMsgObj2(&MA::inMsgRecv, &myobj);
myOutMsgObj.join();
myInMsgObj.join();
myInMsgObj2.join();
cout << "main End of main function execution " << endl; // Finally, execute this sentence , The whole process exits
return 0;
}
Two : On thread pool
<1> Scenario
Server program -> client , Every client , Create a new thread to serve the customer .
(1) Network game ,2 It is impossible for 10000 players to create a new thread for each player , This program doesn't work in this scenario ;
(2) Program stability problem : In the code , Occasionally create a thread of this code , This kind of writing , It makes people feel uneasy ;
Thread pool : Put a bunch of threads together , Unified management . This unified management debugging , Recycle the thread mode , It's called thread pool .
<2> Realization way :
When the program starts , Create a certain number of threads at one time .10,8,100-200, More reassuring , I think the program code is more stable .
3、 ... and : Number of threads created
<1> The number limit of threads ,2000 A thread is basically the limit , Creating another thread will crash .
<2> Recommended number of threads created
(1) Develop programs using certain technologies ;api The interface provider recommends that you create the number of threads = CPU Number 、CPU * 2、CPU * 2 + 2, Follow professional advice and instructions to ; Professional advice to ensure efficient execution of procedures ;
(2) Create multiple threads to complete the business ; A thread is equal to a path ;100 To block recharge , We drive here 110 Threads , That's very appropriate ;
(3)1800 Threads , It is recommended that the number of threads should not exceed 500 individual , Can control the 200 within .
Four :c++11 Multithreaded summary
边栏推荐
- 丰富专业化产品线, 江铃福特领睿·极境版上市
- When I was in the library, I thought of the yuan sharing mode
- Halcon's region: features of multiple regions (5)
- next(iter(dataloader))的一点点体会
- pycharm的plt.show()如何保持不关闭
- LM06丨仅用成交量构造抄底摸顶策略的奥秘
- 清华&商汤&上海AI&CUHK提出Siamese Image Modeling,兼具linear probing和密集预测性能!
- [code Capriccio - dynamic planning] t583. Deleting two strings
- 在国金证券开户怎么样?开户安全吗?
- js强制转换
猜你喜欢

【uniapp】uniapp手机端使用uni.navigateBack失效问题解决

9、智慧交通项目(2)

LeetCode——226. 翻轉二叉樹(BFS)

分布式架构概述

清华&商汤&上海AI&CUHK提出Siamese Image Modeling,兼具linear probing和密集预测性能!

MySql 导出数据库中的全部表索引

Today, I met a "migrant worker" who took out 38K from Tencent, which let me see the ceiling of the foundation

类型多样的石膏PBR多通道贴图素材,速来收藏!

深层次安全定义剖析及加密技术

分布式缓存/缓存集群简介
随机推荐
Microservice architecture practice: business management background and SSO design: SSO design
如何将应用加入到deviceidle 白名单?
Necessary decorator mode for 3 years' work
halcon之区域:多种区域(Region)特征(5)
Number of solutions for knapsack problem
Live broadcast preview | how can programmers improve R & D efficiency? On the evening of June 21, the video number and station B will broadcast live at the same time. See you or leave!
Strength and appearance Coexist -- an exclusive interview with Liu Yu, a member of Apache pulsar PMC
Vue--vuerouter cache routing component
MySQL index
玩转Linux,轻松安装配置MySQL
Troubleshooting ideas that can solve 80% of faults!
padding百分比操作
#26class中get和set设置
二分查找法-1
ZCMU--1367: Data Structure
How to add an application to the deviceidle whitelist?
Ndroid development from introduction to mastery Chapter 2: view and ViewGroup
[recommendation system learning] recommendation system architecture
RSA概念详解及工具推荐大全 - lmn
【QNX】命令