boost bind及多執行緒
阿新 • • 發佈:2019-01-09
之前專案中用到學習了一下,今天總結總結
bind生成一個仿函式,可以配接任意函式(裸函式,類成員函式,靜態成員函式)指定引數傳遞方式個數。在需要仿函式的地方(accumulate,for_each等)超級好用
#include <iostream> #include <algorithm> #include <numeric> #include <map> #include <vector> #include <boost/bind.hpp> using namespace std; struct comp { pair<double, double> operator()(const pair<double, double>& init, double x) const { return make_pair(init.first + x, init.second + x*x); } }; class A { public: pair<double, double> sum(const pair<double, double>& init, double x) const { return make_pair(init.first + x, init.second + x*x); } }; pair<double, double> sum(const pair<double, double>& init, double x, double y, double z) { return make_pair(init.first + x + y, init.second + x*x); } pair<double, double> sum2(const pair<double, double>& init, double x, double y) { return make_pair(init.first + x + y, init.second + y*y); } int main () { vector<double> test; for(int i = 0; i < 100; ++i) { test.push_back(i); } A a; double y = 0.0; //a.sum(); A::sum(*this) //pair<double, double> re = accumulate(test.begin(), test.end(), make_pair(0, 0), comp()); //pair<double, double> re = accumulate(test.begin(), test.end(), make_pair(0, 0), boost::bind((&A::sum), &a, _1, _2)); pair<double, double> re = accumulate(test.begin(), test.end(), make_pair(0, 0), boost::bind(sum, _1, _2, y, y)); //pair<double, double> re2 = boost::bind(sum, _1, _2, y, y)(make_pair(10, 10), 10); pair<double, double> re2 = boost::bind(sum2, _1, y, _2)(make_pair(10, 10), 10); // operator+(_1, _2); cout << re2.first << " " << re2.second << endl; cout << re.first << " " << re.second << endl; return 0; }
boost多執行緒可以三行程式碼搞定。。。bind的使用使得引數傳遞比c語言的不知道方便多少倍
上程式碼
#include <iostream> #include <boost/thread/thread.hpp> #include <boost/thread/locks.hpp> #include <boost/thread/mutex.hpp> #include <boost/bind.hpp> using namespace std; boost::mutex mtx; void show(int i) { boost::unique_lock< boost::mutex > lock(mtx);//建構函式鎖,解構函式解鎖 //mtx.lock(); cout << "wangbing" << i << endl; //mtx.unlock(); } int main() { int thread_num = 8; boost::thread_group group; for(int i = 0; i < thread_num; ++i) { group.create_thread( boost::bind(show, i)); } cout << "xxxxxx" << endl; group.join_all(); return 0; }