当前位置:网站首页>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
边栏推荐
- Leetcode topic [array] -268- missing numbers
- 数字签名论述及生成与优点分析
- 14 MySQL tutorial insert insert data
- 二分查找法-1
- 并发之Synchronized说明
- Platform management background and merchant menu resource management: access control design of platform management background
- Technical scheme design of chain game system development - NFT chain game system development process and source code
- 决策树与随机森林
- 【动态规划】剑指 Offer II 091. 粉刷房子
- 【万字总结】以终为始,详细分析高考志愿该怎么填
猜你喜欢
![[code Capriccio - dynamic planning] t583. Deleting two strings](/img/01/fd9ff51ea1d70188e372e925d8a1c7.png)
[code Capriccio - dynamic planning] t583. Deleting two strings

The latest masterpiece of Alibaba, which took 182 days to produce 1015 pages of distributed full stack manual, is so delicious

牛客网:设计LRU缓存结构 设计LFU缓存结构

Inspirational. In one year, from Xiaobai to entering the core Department of Alibaba, his counter attack

SIGIR 2022 | University of Hong Kong and others proposed the application of hypergraph comparative learning in Recommendation System

有依赖的背包问题

Army chat -- registration of Registration Center

pycharm的plt.show()如何保持不关闭

RSA概念详解及工具推荐大全 - lmn

Halcon's region: features of multiple regions (5)
随机推荐
Problems encountered this week
How does Guosen Securities open an account? Is it safe to open a stock account through the link
Troubleshooting ideas that can solve 80% of faults!
【代码随想录-动态规划】T583、两个字符串的删除操作
Niuke network: Design LRU cache structure design LFU cache structure
Cache breakdown! Don't even know how to write code???
Leetcode HOT100 (22--- bracket generation)
【万字总结】以终为始,详细分析高考志愿该怎么填
Play with Linux and easily install and configure MySQL
The high concurrency system is easy to play, and Alibaba's new 100 million level concurrent design quick notes are really fragrant
Use FST JSON to automatically generate faster JSON serialization methods
Microservice architecture practice: user login and account switching design, order query design of the mall
next(iter(dataloader))的一点点体会
Technical scheme design of chain game system development - NFT chain game system development process and source code
直播预告|程序员进击,如何提升研发效能?6月21日晚视频号、B站同步直播,不见不散!
Cloud native 02: Alibaba cloud cloud efficient flow pipeline
transforms.RandomCrop()的输入只能是PIL image 不能是tensor
[code Capriccio - dynamic planning] t583. Deleting two strings
She said she was tired! So tired! I want to change my career
Notes on flowus