gpt4 book ai didi

c++ - 如何在 C++ 中使用 和一维数组进行矩阵乘法?

转载 作者:搜寻专家 更新时间:2023-10-31 02:10:46 24 4
gpt4 key购买 nike

我正在尝试使用线程进行矩阵乘法。但是我没有得到正确的值。由于矩阵可能非常大,我使用堆内存。因此矩阵存储在一维数组中。

矩阵始终是方阵,因此行数和列数等于数组长度的平方根。如果数组长度为 16,则行数为 4,列数也为 4。

我不能使用 std::vector 所以这就是使用 std::unique_ptr 的原因。

有 4 个线程,每个线程接收原始数组的 1/4 进行处理。由于矩阵乘法的性质,这不起作用,而且我似乎找不到正确的解决方案。 如何将任务拆分为 4 个线程

auto matrixmultiplication(float* &array1, float* &array2, int arrayLength) {
unique_ptr<float[]> arrayOut(new float[arrayLength]);
auto numberOfThreads = 4;
auto widthMatrix = (int)sqrt(arrayLength);
auto elementsPerThread = (int)sqrt(arrayLength / numberOfThreads);

auto mul = [](auto* array1, auto* array2, auto* array3, auto dimension) {
for (auto x = 0; x < dimension; x++) {
for (auto y = 0; y < dimension; y++) {
array3[dimension * x + y] = 0;
for (auto z = 0; z < dimension; z++) {
array3[dimension * x + y] += array1[dimension * x + z] * array2[dimension * z + y];
}
}
}
};

vector<thread> threads;
for (auto i = 0; i < numberOfThreads; i++) {
threads.push_back(
thread(
mul,
array1 + i * elementsPerThread,
array2,
arrayOut.get() + i * elementsPerThread,
elementsPerThread
)
);
}
for (auto &thread : threads) {
thread.join();
}
return arrayOut;
};

最佳答案

对于所有线程,我将从第一个矩阵的连续行开始处理,即第 0 个线程将处理第 0 行,第 1 个线程将处理第 1 行,依此类推到第 n 个线程。

在一个线程处理完一行后,它必须跳到线程数的下一行,即如果我有 2 个线程,在第 0 个线程处理完第 0 行后,它将跳到第 2 行并处理它。

让我们看一个工作示例:

#include <iostream>
#include <memory>
#include <vector>
#include <thread>

// multiplies the specified row and column from specified matrices
void multiply(const int* m_1, const int* m_2,
std::size_t size, std::size_t row, std::size_t col, int* m_res) {
for(std::size_t i = 0; i < size; ++i)
m_res[row * size + col] += m_1[row * size + i] * m_2[i * size + col];
}

int main() {
constexpr int N = 3, THREAD_NUM = 2;

// matrices to multiply and a matrix for result
std::unique_ptr<int[]> A(new int[N * N] {
11, 12, 13, 21, 22, 23, 31, 32, 33
});
std::unique_ptr<int[]> B(new int[N * N] {
1, 0, 0, 0, 1, 0, 0, 0, 1
});
std::unique_ptr<int[]> C(new int[N * N] {});

// create vector for running threads then assign threads to its elements
std::vector<std::thread> thread_group(THREAD_NUM);

for(int thread_i = 0; thread_i < THREAD_NUM; ++thread_i)
thread_group[thread_i] = std::thread([&, thread_i]() {

// each thread stars from consecutive rows then steps by
// the number of threads
for(int row = thread_i; row < N; row += THREAD_NUM) {
for(int col = 0; col < N; ++col)
multiply(A.get(), B.get(), N, row, col, C.get());
}
});

for(auto& t : thread_group)
t.join();

// show the result
for(int i = 0; i < N; ++i) {
for(int j = 0; j < N; ++j)
std::cout << (j ? "\t" : "") << C[i * N + j];
std::cout << std::endl;
}
}

关于c++ - 如何在 C++ 中使用 <threads> 和一维数组进行矩阵乘法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44755512/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com