c_cpp threads.c
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp threads.c相关的知识,希望对你有一定的参考价值。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <zconf.h>
#define LEN 4
pthread_t tid[LEN];
struct Mat {
double **macierz;
int r;
int c;
};
struct Result {
struct Mat *mat1;
struct Mat *mat2;
struct Mat *result;
int id;
int poczatek[LEN];
int koniec[LEN];
};
void print_matrix(double **A, int m, int n) {
int i, j;
printf("[");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("%f ", A[i][j]);
}
printf("\n");
}
printf("]\n");
}
void *multiply(void *arg) {
pthread_t id = pthread_self();
struct Result *res = (struct Result *) arg;
int i, j, k;
double s;
for (i = res->poczatek[res->id]; i < res->koniec[res->id]; i++) {
for (j = 0; j < res->mat2->r; j++) {
s = 0;
for (k = 0; k < res->mat2->c; k++) {
s += res->mat1->macierz[i][k] * res->mat2->macierz[k][j];
}
res->result->macierz[i][j] = s;
}
}
print_matrix(res->result->macierz, res->result->r, res->result->c);
}
struct Mat *wczytaj(char *filename) {
FILE *fpa;
double **A;
int ma, na;
int i, j;
double x;
fpa = fopen(filename, "r");
if (fpa == NULL) {
perror("błąd otwarcia pliku");
exit(-10);
}
fscanf(fpa, "%d", &ma);
fscanf(fpa, "%d", &na);
printf("pierwsza macierz ma wymiar %d x %d, a druga ", ma, na);
/*Alokacja pamięci*/
A = malloc(ma * sizeof(double));
for (i = 0; i < ma; i++) {
A[i] = malloc(na * sizeof(double));
}
for (i = 0; i < ma; i++) {
for (j = 0; j < na; j++) {
fscanf(fpa, "%lf", &x);
A[i][j] = x;
}
}
printf("A:\n");
print_matrix(A, ma, na);
struct Mat *result = (struct Mat *) malloc(sizeof(struct Mat));
result->macierz = A;
result->r = ma;
result->c = na;
return result;
}
int main(void) {
struct Mat *m1 = wczytaj("A.txt");
struct Mat *m2 = wczytaj("B.txt");
struct Mat *results = (struct Mat *) malloc(sizeof(struct Mat));
double **C;
int i = 0;
int err;
/*Macierz na wynik*/
C = malloc(m1->c * sizeof(double));
for (i = 0; i < m1->c; i++) {
C[i] = malloc(m2->r * sizeof(double));
}
results->macierz = C;
results->r = m1->c;
results->c = m2->r;
struct Result *result = (struct Result *) malloc(sizeof(struct Result));
result->mat1 = m1;
result->mat2 = m2;
result->result = results;
for (int j = 0; j < LEN; ++j) {
result->poczatek[j] = (result->mat1->r / LEN * j);
result->koniec[j] = result->mat1->r / LEN + (result->mat1->r / LEN * j) - 1;
printf("Poczatek %d, koniec %d\n", result->poczatek[j], result->koniec[j]);
}
while (i < LEN) {
result->id = i;
err = pthread_create(&(tid[i]), NULL, &multiply, (void *) result);
if (err != 0)
printf("\ncan't create thread :[]");
else
printf("\n Thread created successfully\n");
i++;
}
for(i= 0; i < LEN; i++){
pthread_join(tid[i], NULL);
}
print_matrix(result->result->macierz, result->result->r, result->result->c);
sleep(5);
return 0;
}
以上是关于c_cpp threads.c的主要内容,如果未能解决你的问题,请参考以下文章