C++11中function对象作回调函数的用法
来源:互联网 发布:保护眼睛的电脑软件 编辑:程序博客网 时间:2024/05/18 08:13
主要参考了这篇博文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;}
0 0
- C++11中function对象作回调函数的用法
- tr1::function对象作回调函数技术总结
- VC中回调函数的用法
- VC中回调函数的用法
- VC中回调函数的用法
- php中应用回调函数的实际例子说明回调函数的用法
- C语言回调函数用法示例
- C语言中的回调函数(Callback Function)
- C语言中的回调函数(Callback Function)
- 回调函数中JSON对象的解析方式
- 回调函数(Callback Function)
- 回调函数 Callback Function
- 回调函数callback function
- 回调函数(Callback Function)
- callback function 回调函数
- 回调函数 callback function
- 如何作一个类的回调函数
- 如何作一个类的回调函数
- linux进程描述符task_struct详解
- ubuntu下彻底卸载mysql后重新安装——解决忘记mysql的root密码问题
- 二分查找
- Java_Pro1_枚举类入门_08_08
- Eclipse快捷键
- C++11中function对象作回调函数的用法
- volley总结
- HDU 5024 Wang Xifeng's Little Plot 暴搜
- poj 1636 Prison rearrangement
- 详细讲解HTML 5中视频和音频核心事件
- scala spark maven 配置文件 pom.xml
- java回忆录—I/O流详解补充
- RDD之aggregate操作
- JAVA 递归 汉诺塔