c++ vector 并发
时间: 2024-01-21 10:14:58 浏览: 89
C++ vector
C++中的vector可以通过并发来提高程序的性能。下面是两种实现并发的方式:
1. 单线程版:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
int GetSum(vector<int>::iterator first, vector<int>::iterator last) {
return accumulate(first, last, 0); // 调用C++标准库算法
}
int main() {
vector<int> largeArrays;
for (int i = 0; i < 100000000; i++) {
if (i % 2 == 0)
largeArrays.push_back(i);
else
largeArrays.push_back(-1 * i);
}
int res = GetSum(largeArrays.begin(), largeArrays.end());
return 0;
}
```
2. 多线程版:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <thread>
using namespace std;
int GetSum(vector<int>::iterator first, vector<int>::iterator last) {
return accumulate(first, last, 0); // 调用C++标准库算法
}
int main() {
vector<int> largeArrays;
for (int i = 0; i < 100000000; i++) {
if (i % 2 == 0)
largeArrays.push_back(i);
else
largeArrays.push_back(-1 * i);
}
int numThreads = 5;
vector<thread> threads;
int chunkSize = largeArrays.size() / numThreads;
auto first = largeArrays.begin();
auto last = first + chunkSize;
for (int i = 0; i < numThreads; i++) {
threads.push_back(thread(GetSum, first, last));
first = last;
last += chunkSize;
}
int res = 0;
for (auto& t : threads) {
t.join();
res += GetSum(first, last);
}
return 0;
}
```
阅读全文