Advertisement
Sanlover

Untitled

Jun 7th, 2022
1,106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 4.15 KB | None | 0 0
  1. #include <iomanip>
  2. #include <iostream>
  3. #include <mutex>
  4. #include <thread>
  5. #include <vector>
  6. using namespace std;
  7. static std::mutex mtx;
  8.  
  9. void summaryMethod(int* row, const size_t& size, int& summary)
  10. {
  11.     ////const thread::id this_id = this_thread::get_id();   // для показа работы многопоточности
  12.     ////mtx.lock();                                         // для показа работы многопоточности
  13.     ////cout << this_id << " start working" << endl;        // для показа работы многопоточности
  14.     ////mtx.unlock();                                       // для показа работы многопоточности
  15.  
  16.     // Временная сумма строки
  17.     int value = 0;
  18.     // Нашёлся ли чётный элемент
  19.     bool isFound = false;
  20.     // Бежим по строке
  21.     for (size_t i = 0; i < size; i++)
  22.     {
  23.         // Если не нашли и текущий элемент чётный,
  24.         if (!isFound && row[i] % 2 == 0)
  25.         {
  26.             // то нашли
  27.             isFound = true;
  28.         }
  29.         // Если число было найдено,
  30.         if (isFound)
  31.         {
  32.             // то добавляем число
  33.             value += row[i];
  34.         }
  35.     }
  36.     // блокируем мьютекс
  37.     mtx.lock();
  38.     // записываем в общую переменную наше подсчитанное число
  39.     summary += value;
  40.     ////cout << this_id << " stop working" << endl;             // для показа работы многопоточности
  41.     // разблокирываем
  42.     mtx.unlock();
  43. }
  44.  
  45. int getSummary(int** matrix, const size_t& rows, const size_t& cols, const size_t& nThreads)
  46. {
  47.     // создаём вектор под потоки
  48.     vector<thread> threads;
  49.     // резервируем место под количество потоков
  50.     threads.reserve(nThreads);
  51.     // общая сумма со всех строк
  52.     int summary = 0;
  53.     // id - индекс строки, threadCounter - счётчик потоков
  54.     size_t id = 0, threadCounter = 0;
  55.     // если мы ещё не на последей строке
  56.     while (id != rows)
  57.     {
  58.         // если мы ещё не на последей строке и не запустили максимальное количество потоков
  59.         while (id != rows && threadCounter != nThreads)
  60.         {
  61.             // запускаем новый поток. (ref - объект-ссылка, чтобы другой поток мог его изменить через ссылку)
  62.             threads.emplace_back(
  63.                 summaryMethod, matrix[id++], cols, ref(summary));
  64.             // добавляем количество запущенных
  65.             threadCounter++;
  66.         }
  67.         // Пробегаем по всем потокам и присоединяем их к основному.
  68.         for (auto& thread : threads)
  69.         {
  70.             thread.join();
  71.         }
  72.         // Очищаем потоки т.к. они отработали
  73.         threads.clear();
  74.         // зануляем кол-во запущенных
  75.         threadCounter = 0;
  76.     }
  77.     // Возвращаем подсчитанное
  78.     return summary;
  79. }
  80.  
  81. void printMatrix(int** matrix, const size_t& rows, const size_t& cols)
  82. {
  83.     for (size_t i = 0; i < rows; i++)
  84.     {
  85.         for (size_t j = 0; j < cols; j++)
  86.         {
  87.             cout << setw(3) << matrix[i][j];
  88.         }
  89.         cout << endl;
  90.     }
  91. }
  92.  
  93.  
  94. int main()
  95. {
  96.     size_t rows, cols;
  97.  
  98.     cout << "Enter sizes: " << endl;
  99.     cout << "Rows = ";
  100.     cin >> rows;
  101.     cout << "Cols = ";
  102.     cin >> cols;
  103.  
  104.     auto matrix = new int*[rows];
  105.     for (size_t i = 0; i < rows; i++)
  106.     {
  107.         matrix[i] = new int[cols];
  108.     }
  109.  
  110.     cout << endl << "Fill the matrix:" << endl;
  111.     for (size_t i = 0; i < rows; i++)
  112.     {
  113.         for (size_t j = 0; j < cols; j++)
  114.         {
  115.             cout << "[" << i << "][" << j << "]= ";
  116.             cin >> matrix[i][j];
  117.         }
  118.     }
  119.     cout << endl << "Your matrix:" << endl;
  120.     printMatrix(matrix, rows, cols);
  121.  
  122.     size_t nThreads;
  123.     cout << "Etner the amount of threads you want to use: ";
  124.     cin >> nThreads;
  125.     // Если больше, чем доступно
  126.     if (nThreads > thread::hardware_concurrency())
  127.     {
  128.         cout << "Unable to set " << nThreads << " when possible only " << thread::hardware_concurrency();
  129.         return 1;
  130.     }
  131.  
  132.     cout << "Summary = " << getSummary(matrix, rows, cols, nThreads);
  133.     return 0;
  134. }
  135.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement