传奇传世复古资源的暂存站!

一个完整的Pthreads矩阵-向量乘法程序

2024.5.22 源码下载 36 编辑
推广
推荐工具 不会架设,不会配置,找不到引擎,找不到登录器?

GGM 助手一键架设,一键修复。

  • 认引擎 自动识别彩虹3 / 星河 / 龙腾 / AFT3 / U2 / 飘逸
  • 对组件 与标准组件逐项比对,缺的补、旧的换
  • 修配置 路径重算成相对路径、端口与游戏名统一,换台机器不用再改
  • 补目录 打包丢掉的空目录自动补齐,不再报路径错误
  • 一键启动 按顺序拉起数据库、登录服务、主引擎与三个网关
  • 自愈程序持续更新 无法修复的版本直接上报,管理员帮忙修复
免费下载 GGM 助手 · 逛在线版本库 Windows 10 / 11 · 免费 · 版本库每个包都标注了「已通过 GGM 部署验证」

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define MATRIX_SIZE 3
#define VECTOR_SIZE 3
#define NUM_THREADS 2

// Matrix and vector
int matrix[MATRIX_SIZE][MATRIX_SIZE];
int vector[VECTOR_SIZE];
int result[MATRIX_SIZE];

// Mutex for accessing result array
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

// Function executed by each thread
void *multiply(void *arg) {
int thread_id = *((int *)arg);
int start = thread_id * (MATRIX_SIZE / NUM_THREADS);
int end = (thread_id + 1) * (MATRIX_SIZE / NUM_THREADS);

// Compute partial result
for (int i = start; i < end; ++i) {
int sum = 0;
for (int j = 0; j < MATRIX_SIZE; ++j) {
sum += matrix[i][j] * vector[j];
}

// Protect shared result array with mutex
pthread_mutex_lock(&mutex);
result[i] = sum;
pthread_mutex_unlock(&mutex);
}

pthread_exit(NULL);
}

int main() {
pthread_t threads[NUM_THREADS];
int thread_ids[NUM_THREADS];

// Initialize matrix and vector
printf("Matrix:\n");
for (int i = 0; i < MATRIX_SIZE; ++i) {
for (int j = 0; j < MATRIX_SIZE; ++j) {
matrix[i][j] = rand() % 10;
printf("%d ", matrix[i][j]);
}
printf("\n");
}

printf("\nVector:\n");
for (int i = 0; i < VECTOR_SIZE; ++i) {
vector[i] = rand() % 10;
printf("%d\n", vector[i]);
}

// Create threads
for (int i = 0; i < NUM_THREADS; ++i) {
thread_ids[i] = i;
pthread_create(&threads[i], NULL, multiply, &thread_ids[i]);
}

// Join threads
for (int i = 0; i < NUM_THREADS; ++i) {
pthread_join(threads[i], NULL);
}

// Print result
printf("\nResult:\n");
for (int i = 0; i < MATRIX_SIZE; ++i) {
printf("%d\n", result[i]);
}

pthread_mutex_destroy(&mutex);
return 0;
}

评论

发表评论必须先登陆, 您可以 登陆 或者 注册新账号 !


在线咨询: 问题反馈
客服QQ:174666394

有问题请留言,看到后及时答复