代码:
1 #include "stdio.h" 2 #include <iostream> 3 #include <thread> 4 #include <vector> 5 6 //回调函数类 7 class MsgDeal 8 { 9 public: 10 MsgDeal() : value_(0){}; 11 void CallBack(std::string str, int num) 12 { 13 value_ = num; 14 std::cout << str << "‘s value is " << value_ << std::endl; 15 } 16 17 int GetValue() 18 { 19 return value_; 20 } 21 22 private: 23 unsigned short value_; 24 }; 25 26 //线程掌控类 27 class ThreadControl 28 { 29 public: 30 ThreadControl() : stop_flag_(false){}; 31 32 template <class T> 33 void Register(T &deal) 34 { 35 threads_.push_back(std::thread(&ThreadControl::DataDeal<T>, this, std::ref(deal))); 36 } 37 38 void StopThread(){}; 39 40 private: 41 template <class T> 42 void DataDeal(T &deal) 43 { 44 unsigned short count = 0; 45 while (true) 46 { 47 deal.CallBack(typeid(deal).name(), ++count); 48 std::this_thread::sleep_for(std::chrono::seconds(1)); 49 } 50 } 51 52 bool stop_flag_; 53 std::vector<std::thread> threads_; 54 }; 55 56 template <class T> 57 void Test(T data) 58 { 59 data.CallBack(); 60 }; 61 62 int main() 63 { 64 MsgDeal msg_deal; 65 ThreadControl thread_control; 66 thread_control.Register(msg_deal); 67 68 std::this_thread::sleep_for(std::chrono::milliseconds(500)); 69 while (true) 70 { 71 std::cout << "get value : " << msg_deal.GetValue() << std::endl; 72 std::this_thread::sleep_for(std::chrono::seconds(1)); 73 } 74 thread_control.StopThread(); 75 76 std::cout 77 << "exit~~~~" << std::endl; 78 return 0; 79 }
编译环境:ubuntu20
编译指令:g++ main.c -lpthread
1、std::ref的使用。
std::ref只是包装器,此处给线程函数传值时必须使用std::ref包装。
如果在其他地方使用了std::ref,记得使用它的接口(get())调出被包装的数据。否则会报”对象无xx成员函数“
2、线程函数的参数如果不声明为引用的的话,传入的值将不会是引用。