Answer the question
In order to leave comments, you need to log in
How to make threads work with c++ class?
It is necessary to look for numbers greater than the one entered in the matrix so that a separate thread is allocated for each row of the matrix.
My code doesn't work with my class and throws a huge error that I can't figure out. (there is no problem when working with ordinary types, such as int primes)
#include "Matrix.h"
int main() {
std::int32_t number = 5;
Matrix matrix;
matrix.printMatrix();
std::cout << matrix.findMoreThanNumber(number) << std::endl;
return 0;
}
#ifndef LAB9_MATRIX_H
#define LAB9_MATRIX_H
#include <iostream>
#include <ctime>
#include "mingw.thread.h"
#include <chrono>
#include <vector>
class Matrix {
public:
Matrix();
void printMatrix() const;
void findNumberInRow(const std::vector<std::int32_t> &row, const std::int32_t number);
std::int32_t findMoreThanNumber(const std::int32_t number);
private:
std::int32_t rows, cols, count;
std::vector<std::vector<std::int32_t>> matrix;
};
#endif // LAB9_MATRIX_H
#include "Matrix.h"
Matrix::Matrix() : rows(5), cols(5), count(0), matrix(rows) {
srand(time(NULL));
for (std::vector<int>& col : matrix)
{
col = std::vector<int>(cols);
}
for (std::size_t i = 0; i < rows; i++) {
for (std::size_t j = 0; j < cols; j++) {
matrix[i][j] = rand() % 10;
}
}
}
void Matrix::printMatrix() const {
for (std::size_t i = 0; i < rows; i++) {
for (std::size_t j = 0; j < cols; j++) {
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
}
void Matrix::findNumberInRow(const std::vector<std::int32_t> &row, const std::int32_t number) {
std::cout << "Thread ID = " << std::this_thread::get_id() << " for" << std::endl;
for (std::size_t i = 0; i < rows; i++) {
std::cout << row[i] << " ";
if (row[i] > number) {
count++;
}
}
std::cout << std::endl;
}
std::int32_t Matrix::findMoreThanNumber(std::int32_t number) {
std::vector<std::thread> threads;
for (std::size_t i = 0; i < cols; i++) {
std::thread thread(findNumberInRow, matrix[i], number);
threads.push_back(std::move(thread));
}
for (std::thread& thread : threads) {
thread.join();
}
return count;
}
Answer the question
In order to leave comments, you need to log in
You are passing a non-static class method to std::thread. It cannot be passed as a normal function. It can only be called on some object. Where will thread take this object?
There are 2 options - pass a lambda that will capture this and call the object's method on it.
Or, as shown here , pass there &Matrix::findNumberInRow
with the first argument this.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question