-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparallelFind.hpp
More file actions
41 lines (35 loc) · 1.24 KB
/
parallelFind.hpp
File metadata and controls
41 lines (35 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#ifndef _PARALLEL_FIND_HPP_
#define _PARALLEL_FIND_HPP_
#include <future>
#include <algorithm>
template<class InputIterator, class T>
InputIterator parallelFind (InputIterator first, InputIterator last, const T& val)
{
int dist=std::distance(first,last);
int coreCount = std::thread::hardware_concurrency();
std::future<InputIterator> th[coreCount];
for(int i=0;i<coreCount;++i){
if(i!=coreCount-1){
th[i]=std::move(std::async(std::launch::async,[&first,&last,&val,coreCount,dist,i]{return std::find(std::next(first,(dist*i/coreCount)),std::next(first,(dist*(i+1)/coreCount)),val);}));
}else
{
th[i]=std::move(std::async(std::launch::async,[&first,&last,&val,coreCount,dist,i]{return std::find(std::next(first,(dist*i/coreCount)),last,val);}));
}
}
InputIterator result;
for(int i=0;i<coreCount;++i){
if(i!=coreCount-1){
result = th[i].get();
if(result!=std::next(first,(dist*(i+1)/coreCount))){
return result;
}
}else{
result = th[i].get();
if(result!=last){
return result;
}
}
}
return last;
}
#endif