C++11 std::bind笔记
2016-07-14 21:24
567 查看
std::bind简介
bind是这样一种机制,它可以预先把指定可调用实体的某些参数绑定到已有的变量,产生一个新的可调 用实体,这种机制在回调函数的使用过程中也颇为有用。C++11中提供了std::bind,可以说是一种飞跃的提升,bind本身是一种延迟计算的思想,它本身可以绑定普通函数、全局函数、静态函数、类静态函数甚至是类成员函数。
代码
下面提供绑定一般函数,成员函数的方法,以及占位符的简单应用#include <iostream> #include <memory> #include <thread> #include <mutex> using namespace std; mutex mutex1; class A { private: int x; public: A(int x):x(x) { cout<<"constructor"<<endl; } void print() { cout<<"x="<<x<<endl; } ~A() { cout<<"destructor"<<endl; } }; void threadtask1(shared_ptr<A> a) { mutex1.lock(); cout<<"thread task1 count="<<a.use_count()<<endl; a->print(); mutex1.unlock(); } void threadtask2(shared_ptr<A> a) { mutex1.lock(); cout<<"thread task2 count="<<a.use_count()<<endl; a->print(); mutex1.unlock(); } class B { public: void threadtask3(shared_ptr<A> a) { mutex1.lock(); cout<<"thread task3 count="<<a.use_count()<<endl; a->print(); mutex1.unlock(); } }; int main() { B b; shared_ptr<A> a(new A(3)); auto f1 = bind(threadtask2,a); auto f2 = bind(&B::threadtask3,b,placeholders::_1); thread thread1(threadtask1,a); thread thread2(f1); thread thread3(f2,a); thread1.join(); thread2.join(); thread3.join(); return 0; }
输出结果如下
注意点:
因为我使用的是g++编译的,在使用线程的时候需要添加-pthread,否则运行的时候会出现**terminate called after throwing an instance of ‘std::system_error’
what(): Operation not permitted**的错误
相关文章推荐
- std::function 与 std::bind 的基础使用
- C++14:std::bind和std::function
- July 14th 模拟赛C T2 数码问题 Solution
- C++11 容器Array
- C++Primer课后练习exe6.33
- MFC中程序的延时
- Emacs下编译C++/C程序<转>
- Binary Tree Level Order Traversal II
- C++ 模板类的实现为何放在.h中
- 洛谷 P1969 [NOIP2013 D2T1] 积木大赛
- c语言中long long的用法
- c/c++中的extern
- C语言 程序 阶乘尾数零的个数
- Merge k Sorted Lists
- 常见C++面试问题总结1
- soci-mysq编译
- 关于java格式标示符与c语言格式标示符的误区?
- Valid Palindrome
- 统计整型参数的值为1的二进制位的个数
- C++ 强制转换