主要参考了这篇博文http://www.cnblogs.com/inevermore/p/4038498.html,感谢原作者。
Thread中的函数回调方法,保存着以后使用。
#ifndef THREAD_H_
#define THREAD_H_
#include <boost/noncopyable.hpp>
#include <functional>
#include <pthread.h>
class Thread : boost::noncopyable
{
public:
typedef std::function<void ()> 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<Thread*>(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;
}