zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C++回调demo(线程版)(三十八)

C++线程 Demo 回调 三十八
2023-09-14 09:09:57 时间

1.代码示例  

#include <iostream>
#include <string>
#include <pthread.h>
using namespace std;
typedef void (*MyFun)(int n, string str);

class Call
{
private:
  MyFun myFun;
public:
  void SetFun(MyFun _myFun)
    {
      myFun = _myFun;
    }
  void LetRun(int n, string str)
    {
      myFun(n, str);
    }
};

Call call;

//定义在类中则必须是静态成员函数
static void Test(int n, string str)   
{
  cout << "n = "<< n << " str = " << str <<endl;
}

//定义在类中则必须是静态成员函数
static void *detectd(void* data){
  //call
  call.LetRun(*(int *)data,"Callback Success!");
  return 0;
}

int main()
{
 //调回调函数的接口,并传入一个函数作为参数
 call.SetFun(Test);
 pthread_t tid; 
 int data = 1234;
 pthread_create(&tid, NULL, detectd, &data);
 pthread_join(tid,NULL);
 return 0;
}