基本思想:复习一下c++的多线程和回调函数使用
#include<functional>
#include <iostream>
#include <thread>
#include <vector>
using namespace std;
void fun(int &x, int &y) {
cout << "x=" << x << endl << "y=" << y << endl;
x += 100;
y += 100;
}
void sum(vector<int>::iterator first, vector<int>::iterator end, int &result) {
for (auto it = first; it < end; it++) {
result = result + (*it);
}
}
int main() {
int a = 0;
int b = 100;
function<void()> f1 = bind(fun, a, ref(b));//回调函数
f1();
cout << "a=" << a << endl << "b=" << b << endl;
function<void(int &, int &)> f2 = fun;
f2(a, ref(b)); //对于绑定函数使用ref传递引用
cout << "a=" << a << endl << "b=" << b << endl;
int c=5;
int &d=c;
d=d+1;
cout<<d<<endl;
int e=ref(c);
cout<<e<<endl;
int result1 = 0;
int result2 = 0;
int result3 = 0;
int result4 = 0;
int result5 = 0;
vector<int> sequenece;
sequenece.reserve(8000);
for (int i = 0; i < 8000; i++) {
sequenece.push_back(i);
}
clock_t start, ends;
start = clock();
thread first(sum, sequenece.begin(), sequenece.begin() + 2000, ref(result1));
thread second(sum, sequenece.begin() + 2000, sequenece.begin() + 4000, std::ref(result2));
thread third(sum, sequenece.begin() + 4000, sequenece.begin() + 6000, std::ref(result3));
thread fourth(sum, sequenece.begin() + 6000, sequenece.end(), std::ref(result4));
first.join(); // 阻塞主线程,等待子线程完成 first.detach() 主线程继续执行 子线程也继续执行
second.join();
third.join();
fourth.join();
ends = clock();
cout << (result1 + result2 + result3 + result4) << endl << ends - start << "s" << endl;
start = clock();
for (vector<int>::iterator it = sequenece.begin(); it != sequenece.end(); it++) {
result5 = result5 + *it;
}
ends = clock();
cout << (result5) << endl << ends - start << "s" << endl;
return 0;
}
显示
/home/ubuntu/CLionProjects/test/cmake-build-debug/test
x=0
y=100
a=0
b=200
x=0
y=200
a=100
b=300
6
6
31996000
454s
31996000
208s
Process finished with exit code 0