
这里我们将看到如何使用多线程环境执行矩阵加法和减法。 pthread用于在C或C++中同时执行多个线程。
有两个矩阵A和B。每个矩阵的阶数为(m x n)。每个线程将获取每一行,并执行加法或减法。因此,对于 m 行,有 m 个不同的线程。
示例
#include#include #include #include #define CORE 3#define MAX 3using namespace std;int AMat[MAX][MAX] = {{10, 20, 30}, {40, 50, 60}, {70, 80, 50}};int BMat[MAX][MAX] = {{80, 60, 20}, {30, 20, 15}, {10, 14, 35}};pthread_t thread[CORE * 2];int add[MAX][MAX], sub[MAX][MAX];void* addMatrices(void* arg) { intptr_t core = (intptr_t)arg; // Each thread computes 1/3rd of matrix addition for (int i = core * MAX / 3; i < (core + 1) * MAX / 3; i++) { for (int j = 0; j < MAX; j++) { add[i][j] = AMat[i][j] + BMat[i][j]; } }}void* subtraction(void* arg) { intptr_t core = (intptr_t)arg; // Each thread computes 1/3rd of matrix subtraction for (int i = core * MAX / 3; i < (core + 1) * MAX / 3; i++) { for (int j = 0; j < MAX; j++) { sub[i][j] = AMat[i][j] - BMat[i][j]; } }}void display(){ cout << "Matrix A: " << endl; for(int i = 0; i < MAX; i++) { for(int j = 0; j < MAX; j++) { cout << AMat[i][j] << " "; } cout << endl; } cout << "nMatrix B: " << endl; for(int i = 0; i < MAX; i++) { for(int j = 0; j < MAX; j++) { cout << BMat[i][j] << " "; } cout << endl; }}void displayRes(){ cout << "nAddition: " << endl; for(int i = 0; i < MAX; i++) { for(int j = 0; j < MAX; j++) { cout << add[i][j] << " "; } cout << endl; } cout << "nSubtraction: " << endl; for(int i = 0; i < MAX; i++) { for(int j = 0; j < MAX; j++) { cout << sub[i][j] << " "; } cout << endl; }}main() { display(); int step = 0; for (int i = 0; i < CORE; i++) { pthread_create(&thread[i], NULL, &addMatrices, (void*)step); pthread_create(&thread[i + CORE], NULL, &subtraction, (void*)step); step++; } for (int i = 0; i < CORE * 2; i++) { pthread_join(thread[i], NULL); } displayRes();}
输出
Matrix A:10 20 3040 50 6070 80 50Matrix B:80 60 2030 20 1510 14 35Addition:90 80 5070 70 7580 94 85Subtraction:-70 -40 1010 30 4560 66 15
以上就是使用pthread在C/C++中实现矩阵的加法和减法的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1443908.html
微信扫一扫
支付宝扫一扫