C++並發類成員函數調用(練習1)

來源:互聯網
上載者:User

標籤:ble   with   and   bool   his   condition   函數調用   std   type   

一般類成員函數開線程格式 std::thread t1(&類名::函數,&執行個體化對象,參數....) ||std::thread t1(std::bind(&&類名::函數,&執行個體化對象,參數....))

 1 #include <iostream> 2 #include <mutex> 3 #include <thread> 4 #include <vector> 5 #include <string> 6 #include <condition_variable> 7 #include <future> 8  9 10 template<typename T>11 class vector_safe12 {13 public:14     vector_safe():ready(false),proccess(false){}15 public:16     void push(T& value)17     {18         std::unique_lock<std::mutex> m_guard(mut);19         vec.push_back(value);20         ready=true;21         m_guard.unlock();22         condit_va.notify_one();23     }24     void get_and_pop(T& value)25     {26         std::unique_lock<std::mutex> m_guard(mut);27         condit_va.wait(m_guard,[this](){return ready;});//wait-------線程完畢資料;28                        29         value=vec.front();30         vec.pop_back();31         proccess=true;32          m_guard.unlock();33     34     }35 private:36     std::vector<T> vec;37     std::mutex mut;38     std::condition_variable condit_va;39     bool ready;40     bool proccess;41 42 };43 vector_safe<std::string> obj;44 45 int main()46 {47     48         std::string str1("this is dream");49         std::string str2("沒覆蓋?");50     std::thread t1(std::bind(&vector_safe<std::string>::push,&obj,std::ref(str1)));51     std::thread t2(std::bind(&vector_safe<std::string>::get_and_pop,&obj,std::ref(str2)));52         t1.join();53         t2.join();54         std::cout<<str2<<std::endl;55         return 0;56 }
運行結果:xcode 7.2this is dreamProgram ended with exit code: 0

 

C++並發類成員函數調用(練習1)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.