#include <cstdlib> #include <mutex> #include <random> #include <thread> #include <vector> #include <hpc/aux/slices.hpp> #include <hpc/matvec/gematrix.hpp> #include <hpc/matvec/iterators.hpp> #include <hpc/matvec/print.hpp> #include <hpc/matvec/views.hpp> using namespace hpc; using namespace hpc::aux; using namespace hpc::matvec; struct Guard { Guard(std::mutex& mutex) : mutex(mutex) { mutex.lock(); } ~Guard() { mutex.unlock(); } std::mutex& mutex; }; struct MyRandomGenerator { MyRandomGenerator() : mt(std::random_device()()), uniform(-100, 100) { } double gen() { Guard guard(mutex); return uniform(mt); } private: std::mutex mutex; std::mt19937 mt; std::uniform_real_distribution<double> uniform; }; template < template<typename> class MatrixA, typename T, typename RNG, Require< Ge<MatrixA<T>> > = true > void randomInit(MatrixA<T>& A, RNG& rng) { for (auto [i, j, Aij]: A) { Aij = rng.gen(); (void) i; (void) j; // suppress gcc warning } } int main() { MyRandomGenerator rng; GeMatrix<double> A(51, 7); std::size_t nof_threads = std::thread::hardware_concurrency(); std::vector<std::thread> threads(nof_threads); UniformSlices<std::size_t> slices(nof_threads, A.numRows()); for (std::size_t index = 0; index < nof_threads; ++index) { auto firstRow = slices.offset(index); auto numRows = slices.size(index); threads[index] = std::thread([ A_ = A.view(firstRow, 0, numRows, A.numCols()), &rng ]() mutable { randomInit(A_, rng); }); } for (std::size_t index = 0; index < nof_threads; ++index) { threads[index].join(); } print(A, " %7.2f"); } |