1
0

feat: Initial commit

This commit is contained in:
2024-03-22 16:54:05 +01:00
parent 0d9957a125
commit d993185b89
25 changed files with 641 additions and 0 deletions

79
Lab09/es2.c Normal file
View File

@@ -0,0 +1,79 @@
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#define M_LEN (sizeof(int)+2*sizeof(float))
sem_t *sR;
sem_t *sC[3];
sem_t *sM[3];
float res[3];
int line = 0;
int fin;
void* compute(void* arg) {
int id = *((int *) arg);
free(arg);
int n;
float c, x;
while(1) {
sem_wait(sM[id]);
sem_wait(sR);
int r = lseek(fin, (line*3+id)*M_LEN, SEEK_SET);
if (r == -1) {
pthread_exit(NULL);
}
read(fin, &c, sizeof(float));
read(fin, &x, sizeof(float));
read(fin, &n, sizeof(int));
printf("%d-%d-%d: %f %f %d\n",id,line,r,c,x,n);
sem_post(sR);
res[id] = c;
for (int i = 0; i<n;i++)
res[id]*=x;
sem_post(sC[id]);
}
}
void* merge(void* arg) {
while (1) {
float sum = 0;
for (int i = 0; i < 3; i++) {
sem_wait(sC[i]);
sum += res[i];
}
printf("%f\n", sum);
sleep(3);
line++;
sem_post(sM[0]);
sem_post(sM[1]);
sem_post(sM[2]);
}
}
int main(int argc, char ** argv) {
pthread_t t;
fin = open(argv[1], O_RDONLY);
if (fin == NULL) exit(1);
sR = malloc(sizeof(sem_t));
sem_init(sR,0,1);
for (int i = 0; i<3;i++) {
int * arg=malloc(sizeof(int));
*arg=i;
sC[i] = malloc(sizeof(sem_t));
sM[i] = malloc(sizeof(sem_t));
sem_init(sC[i],0,0);
sem_init(sM[i],0,1);
pthread_create(&t,NULL,compute,(void *)arg);
}
pthread_create(&t,NULL,merge,NULL);
pthread_join(t,NULL);
close(fin);
}