Multiply two 200×200 matrices, giving each of 4 threads a band of result rows; verify against a single-threaded result and print the trace of the product.
Solution
main.cpp
#include <iostream>
#include <thread>
#include <vector>
using Matrix = std::vector<std::vector<long>>;
void multiply_rows(const Matrix& a, const Matrix& b, Matrix& c, std::size_t from, std::size_t to) {
const std::size_t n = a.size();
for (std::size_t i = from; i < to; ++i)
for (std::size_t k = 0; k < n; ++k)
for (std::size_t j = 0; j < n; ++j) c[i][j] += a[i][k] * b[k][j];
}
int main() {
const std::size_t n = 200;
Matrix a(n, std::vector<long>(n)), b(n, std::vector<long>(n));
for (std::size_t i = 0; i < n; ++i)
for (std::size_t j = 0; j < n; ++j) { a[i][j] = static_cast<long>((i + j) % 10); b[i][j] = static_cast<long>((i * j) % 7); }
Matrix parallel(n, std::vector<long>(n, 0)), serial(n, std::vector<long>(n, 0));
std::vector<std::thread> pool;
const std::size_t bands = 4;
for (std::size_t t = 0; t < bands; ++t)
pool.emplace_back(multiply_rows, std::cref(a), std::cref(b), std::ref(parallel), t * n / bands, (t + 1) * n / bands);
for (auto& th : pool) th.join();
multiply_rows(a, b, serial, 0, n);
long trace = 0;
for (std::size_t i = 0; i < n; ++i) trace += parallel[i][i];
std::cout << (parallel == serial ? "results match" : "MISMATCH") << ", trace " << trace << '\n';
return 0;
}
Output Verified by compiling and running
results match, trace 460556
Threads write disjoint rows of the result and only read the inputs, so no synchronisation is needed. The i-k-j loop order is also cache-friendly.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!