Created
November 22, 2015 15:26
-
-
Save nandor/abcf9703b0e0dd93fe0e to your computer and use it in GitHub Desktop.
Computation of maximum using std::thread.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <mutex> | |
#include <thread> | |
#include <vector> | |
#include <iostream> | |
/** | |
* Computes the maximum of a vector in parallel, using n threads. | |
*/ | |
template<typename T> | |
T maximum(const std::vector<T> &vec, size_t n) { | |
const auto chunkSize = vec.size() / n; | |
// Accumulator storing the max value & lock protecting it. | |
auto maxValue = std::numeric_limits<T>::min(); | |
std::mutex maxLock; | |
// Spawn a thread to compute the max value in a chunk. | |
std::vector<std::thread> threads; | |
for (size_t i = 0; i < vec.size(); i += chunkSize) { | |
size_t j = std::min(vec.size(), i + chunkSize); | |
// Spawn a thread executing the lambda function. | |
// The range is captured by value, but the lambda also captures a | |
// reference to the vector, as well as one to the max value and to | |
// the lock. | |
threads.emplace_back([i, j, &vec, &maxLock, &maxValue] () { | |
// Compute the per-chunk maximum. | |
auto maxChunk = vec[i]; | |
for (size_t k = i + 1; k < j; ++k) { | |
maxChunk = std::max(maxChunk, vec[k]); | |
} | |
// Update the global maximum. | |
{ | |
std::unique_lock<std::mutex> locker(maxLock); | |
maxValue = std::max(maxValue, maxChunk); | |
} | |
}); | |
} | |
// Join all threads - block until they finish. | |
for (auto &thread : threads) { | |
thread.join(); | |
} | |
return maxValue; | |
} | |
int main() { | |
std::cout << maximum<int>({1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 3) << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment