一般类成员函数开线程格式 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_safe 12 { 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.2 this is dream Program ended with exit code: 0