1. 程式人生 > 其它 >記錄自己寫回調函式的一些問題

記錄自己寫回調函式的一些問題

程式碼:

 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、執行緒函式的引數如果不宣告為引用的的話,傳入的值將不會是引用。