forked from liuluheng/Cpp-Concurrency-in-Action
-
Notifications
You must be signed in to change notification settings - Fork 0
/
listing_8.10.cpp
45 lines (44 loc) · 1.36 KB
/
listing_8.10.cpp
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
42
43
44
45
template<typename Iterator,typename MatchType>
Iterator parallel_find_impl(Iterator first,Iterator last,MatchType match,
std::atomic<bool>& done)
{
try
{
unsigned long const length=std::distance(first,last);
unsigned long const min_per_thread=25;
if(length<(2*min_per_thread))
{
for(;(first!=last) && !done.load();++first)
{
if(*first==match)
{
done=true;
return first;
}
}
return last;
}
else
{
Iterator const mid_point=first+(length/2);
std::future<Iterator> async_result=
std::async(¶llel_find_impl<Iterator,MatchType>,
mid_point,last,match,std::ref(done));
Iterator const direct_result=
parallel_find_impl(first,mid_point,match,done);
return (direct_result==mid_point)?
async_result.get():direct_result;
}
}
catch(...)
{
done=true;
throw;
}
}
template<typename Iterator,typename MatchType>
Iterator parallel_find(Iterator first,Iterator last,MatchType match)
{
std::atomic<bool> done(false);
return parallel_find_impl(first,last,match,done);
}