|
多线程比单线程的程序耗时还要多:锁用得太频繁
- #include <iostream>
- #include <list>
- #include <string>
- #include <chrono>
- #include <thread>
- class Message
- {
- private:
- std::string m_data;
- public:
- Message(std::string d);
- const std::string& data();
- };
- Message::Message(std::string d) : m_data(d)
- {
- }
- const std::string& Message::data(){
- return m_data;
- }
- std::list<Message> global_message_list;
- void worker(){
- while(!global_message_list.empty()){
- auto iter = global_message_list.begin();
- //do real work and erase it!
- global_message_list.erase(iter);
- }
- }
- // 单线程编程
- //real 0m11.185s
- // user 0m0.186s
- // sys 0m0.117s
- int main(){
- for(int i=0;i<10000;++i){
- global_message_list.push_back("this is a test"+std::to_string(i));
- }
- worker();
- for(int i=0;i<10000;++i){
- std::this_thread::sleep_for(std::chrono::milliseconds(1));
- global_message_list.push_back("the second "+std::to_string(i));
- }
- worker();
- return 0;
- }
复制代码
|
|