菜鸟笔记
提升您的技术认知

c 11中function对象作回调函数的用法-ag真人官方网

thread中的函数回调方法,保存着以后使用。

#ifndef thread_h_
#define thread_h_
#include 
#include 
#include 
class thread : boost::noncopyable
{
public:
    typedef std::function threadcallback;
    thread(threadcallback callback);
    ~thread();
    void start();
    void join();
    static void *runinthread(void *);
private:
    pthread_t threadid_;
    bool isrunning_;
    threadcallback callback_; //回调函数
};
#endif //thread_h_
#include "thread.h"
thread::thread(threadcallback callback)
: threadid_(0),
  isrunning_(false),
  callback_(std::move(callback))//move将表达式转换为右值
{
}
thread::~thread()
{
    if(isrunning_)
    {
        pthread_detach(threadid_);
    }
}
void thread::start()
{
    pthread_create(&threadid_, null, runinthread, this);
    isrunning_ = true;
}
void thread::join()
{
    pthread_join(threadid_, null);
    isrunning_ = false;
}
void *thread::runinthread(void *arg)
{
    thread *pt = static_cast(arg);
    pt->callback_(); //调用回调函数
    return null;
}

(1) 将普通函数作为回调函数

void foo()
{
    while(1)
    {
        printf("foo\n");
        sleep(1);
    }
}
int main(int argc, char const *argv[])
{
    thread t(&foo);
    t.start();
    t.join();
    return 0;
}

(2) 类的成员函数作为回调函数

class foo
{
public:
    void foo(int i)
    {
        while(1)
        {
            printf("foo %d\n", i  );
            sleep(1);
        }
    }
};
int main(int argc, char const *argv[])
{
    foo f;
    int i = 34;
    thread t(bind(&foo::foo, &f, i));
    t.start();
    t.join();
    return 0;
}

(3) 组合一个新的线程

class foo
{
public:
    foo()
    : thread_(bind(&foo::foo, this))
    {
    }
    void start()
    {
        thread_.start();
        thread_.join();
    }
    void foo()
    {
        while(1)
        {
            printf("foo\n");
            sleep(1);
        }
    }
private:
    thread thread_;
};
int main(int argc, char const *argv[])
{
    foo f;
    f.start();
    return 0;
}
网站地图