Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iomanip>
- #include <iostream>
- #include <mutex>
- #include <thread>
- #include <vector>
- using namespace std;
- static std::mutex mtx;
- void summaryMethod(int* row, const size_t& size, int& summary)
- {
- ////const thread::id this_id = this_thread::get_id(); // для показа работы многопоточности
- ////mtx.lock(); // для показа работы многопоточности
- ////cout << this_id << " start working" << endl; // для показа работы многопоточности
- ////mtx.unlock(); // для показа работы многопоточности
- // Временная сумма строки
- int value = 0;
- // Нашёлся ли чётный элемент
- bool isFound = false;
- // Бежим по строке
- for (size_t i = 0; i < size; i++)
- {
- // Если не нашли и текущий элемент чётный,
- if (!isFound && row[i] % 2 == 0)
- {
- // то нашли
- isFound = true;
- }
- // Если число было найдено,
- if (isFound)
- {
- // то добавляем число
- value += row[i];
- }
- }
- // блокируем мьютекс
- mtx.lock();
- // записываем в общую переменную наше подсчитанное число
- summary += value;
- ////cout << this_id << " stop working" << endl; // для показа работы многопоточности
- // разблокирываем
- mtx.unlock();
- }
- int getSummary(int** matrix, const size_t& rows, const size_t& cols, const size_t& nThreads)
- {
- // создаём вектор под потоки
- vector<thread> threads;
- // резервируем место под количество потоков
- threads.reserve(nThreads);
- // общая сумма со всех строк
- int summary = 0;
- // id - индекс строки, threadCounter - счётчик потоков
- size_t id = 0, threadCounter = 0;
- // если мы ещё не на последей строке
- while (id != rows)
- {
- // если мы ещё не на последей строке и не запустили максимальное количество потоков
- while (id != rows && threadCounter != nThreads)
- {
- // запускаем новый поток. (ref - объект-ссылка, чтобы другой поток мог его изменить через ссылку)
- threads.emplace_back(
- summaryMethod, matrix[id++], cols, ref(summary));
- // добавляем количество запущенных
- threadCounter++;
- }
- // Пробегаем по всем потокам и присоединяем их к основному.
- for (auto& thread : threads)
- {
- thread.join();
- }
- // Очищаем потоки т.к. они отработали
- threads.clear();
- // зануляем кол-во запущенных
- threadCounter = 0;
- }
- // Возвращаем подсчитанное
- return summary;
- }
- void printMatrix(int** matrix, const size_t& rows, const size_t& cols)
- {
- for (size_t i = 0; i < rows; i++)
- {
- for (size_t j = 0; j < cols; j++)
- {
- cout << setw(3) << matrix[i][j];
- }
- cout << endl;
- }
- }
- int main()
- {
- size_t rows, cols;
- cout << "Enter sizes: " << endl;
- cout << "Rows = ";
- cin >> rows;
- cout << "Cols = ";
- cin >> cols;
- auto matrix = new int*[rows];
- for (size_t i = 0; i < rows; i++)
- {
- matrix[i] = new int[cols];
- }
- cout << endl << "Fill the matrix:" << endl;
- for (size_t i = 0; i < rows; i++)
- {
- for (size_t j = 0; j < cols; j++)
- {
- cout << "[" << i << "][" << j << "]= ";
- cin >> matrix[i][j];
- }
- }
- cout << endl << "Your matrix:" << endl;
- printMatrix(matrix, rows, cols);
- size_t nThreads;
- cout << "Etner the amount of threads you want to use: ";
- cin >> nThreads;
- // Если больше, чем доступно
- if (nThreads > thread::hardware_concurrency())
- {
- cout << "Unable to set " << nThreads << " when possible only " << thread::hardware_concurrency();
- return 1;
- }
- cout << "Summary = " << getSummary(matrix, rows, cols, nThreads);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement