標籤: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)