我正在試驗執行緒。我的程式應該采用一個向量并通過將其分解為不同的部分并創建一個執行緒來對每個部分求和來求和。目前,我的向量有5 * 10^8元素,我的電腦應該可以輕松處理這些元素。然而,每個執行緒(在我的例子中是 4 個執行緒)的創建需要非常長的時間。我想知道為什么...?
#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
#include <algorithm>
#include <numeric>
#include <ctime>
std::mutex m;
int ans = 0;
void sumPart(const std::vector<int>& v, int a, int b){
std::lock_guard<std::mutex> guard(m);
ans = std::accumulate(v.begin() a, v.begin() b, 0);
}
void sum(const std::vector<int>& v){
//threadCount is 4 on my pc
int threadCount = std::max(2, (int)std::thread::hardware_concurrency()/2);
int sz = v.size()/threadCount;
std::vector<std::thread> threads;
for(int i = 0; i < threadCount; i ){
clock_t start = clock();
threads.push_back(std::thread(sumPart, v, sz*i, sz*(i 1)));
std::cout << "thread " << i 1 << " took " << (clock()-start)/(CLOCKS_PER_SEC/1000) << " ms to create" << std::endl;
}
for(std::thread& t : threads){
t.join();
}
//the leftovers
ans = std::accumulate(v.begin() (threadCount)*sz, v.end(), 0);
}
int main(){
const int N = 5e8;
std::vector<int> v(N);
for(int i = 0; i < N; i ){
v[i] = i;
}
sum(v);
std::cout << ans << std::endl;
}
輸出:
thread 1 took 681 ms to create
thread 2 took 824 ms to create
thread 3 took 818 ms to create
thread 4 took 814 ms to create
1711656320
此外,如果我減少 vector 中的元素數量,創建每個執行緒所需的時間也會減少,這很奇怪......(我也知道我得到了 int 溢位,但這不是重點)
uj5u.com熱心網友回復:
std::thread(sumPart, v, sz*i, sz*(i 1))
執行緒函式的引數被復制,作為創建執行執行緒的一部分。
即使sumPart按值v獲取它的引數也會在內部復制。復制一個包含 500000000 個值的向量需要一點時間。
您可以使用std::ref來有效地通過v參考傳遞給您的執行緒函式。請注意,正如已經提到的,您的鎖將使您的所有執行執行緒成為單執行緒。但是,它們將很快啟動。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/403031.html
標籤:
下一篇:執行緒和同步佇列
