多线程读取矩阵文件+多线程矩阵乘法(C++实现)
生活随笔
收集整理的這篇文章主要介紹了
多线程读取矩阵文件+多线程矩阵乘法(C++实现)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
算法概述
- 矩陣乘法可以在算法層面上進行并行。
- vector< vector > Mat[3]; 這個二維向量數組就是來放做矩陣乘法中的那些矩陣的。Mat[0]是矩陣A,Mat[1]是矩陣B,Mat[2]是乘法的結果矩陣。所以下圖中關于這個就做了類似的修改。
- readMat就是用來讀取特定的矩陣。注意,這里的target矩陣要用指針,如果改成用引用的模式,就會報錯。這可能跟引用的機制有關,具體沒有深入研究過。
- run_test_parallel函數就是用來算結果矩陣的每一行的。
- filenames這個數組,用來放文件名。(注意,需要使用const char* [])
- vt.clear();結束之后,記得將這個線程向量給clear掉,后面也用到了。節省空間。
- if (Mat[0][0].size() == Mat[1].size()) 是用來判斷是否可以進行矩陣乘法的。
- 之后初始化結果矩陣的時候,算法復雜度是O(a+c),而不是一般認為的O(a*c)
- 再來就是計算矩陣乘法,并輸出結果了。
程序
#include <iostream> #include <vector> #include <fstream> #include <thread> using namespace std; vector< vector<int> > Mat[3];void readMat(const char* filename, vector< vector<int> >* target) {int a, b, c;ifstream in(filename);in >> a >> b;for (int i = 0; i < a; ++i) {vector<int> temp;for (int j = 0; j < b; ++j) {in >> c;temp.push_back(c);}(*target).push_back(temp);temp.clear();}in.close(); } void run_test_parallel(int row_index, int column_cntA, int column_cntB) {// Go over every column of matrixBfor (int i = 0; i<column_cntB; i++){// to compute every element of (row_index)-th row of answerMat[2][row_index][i] = 0;// Compute the answer// Number of columns in A = Number of rows in Bfor (int j = 0; j<column_cntA; j++)Mat[2][row_index][i] += Mat[0][row_index][j] * Mat[1][j][i];} } int main() {const char *filenames[] = { "1.txt", "2.txt" };vector<thread> vt;for (int i = 0; i < 2; ++i)vt.push_back(thread(readMat, filenames[i], &Mat[i]));for (int i = 0; i < 2; ++i)vt[i].join();vt.clear();if (Mat[0][0].size() == Mat[1].size()) {int a = Mat[0].size(), b = Mat[1].size(), c = Mat[1][0].size();vector<int> temp;for (int j = 0; j < c; ++j) temp.push_back(0);for (int i = 0; i < a; ++i) Mat[2].push_back(temp);// Create a threads, because there are a rows in Mat[0]// Each thread will be running function "run_test_parallel"for (int i = 0; i<a; i++)vt.push_back(thread(run_test_parallel, i, b, c));for (int i = 0; i<a; i++)vt[i].join();for (int i = 0; i < 2; ++i) {for (int j = 0; j < Mat[i].size(); ++j) {for (int k = 0; k < Mat[i][j].size(); ++k) {cout << Mat[i][j][k] << " ";}cout << endl;}if (i == 0)cout << "MULTIPLED\n";elsecout << "EQUAL TO --->\n";}for (int i = 0; i < a; ++i) {for (int j = 0; j < c; ++j) {cout << Mat[2][i][j] << " ";}cout << endl;}}else {cout << "Can't Multiple!!\n";}system("pause");return 0; }總結
以上是生活随笔為你收集整理的多线程读取矩阵文件+多线程矩阵乘法(C++实现)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 复合高斯积分(节点数小于等于3的版本Py
- 下一篇: 多线程生成随机数组+双线程归并排序(C+