您的位置:首页 > 编程语言 > C语言/C++

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-bind