main_old.c 2.2 KB
#include "matrix.h"
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

struct worker_data{

	matrix *in1, *in2, *out;
	pthread_cond_t work;
	pthread_mutex_t work_mutex;
	pthread_cond_t done;
	pthread_mutex_t done_mutex;

};
typedef struct worker_data worker_data;


void * worker (void * _arg){

	worker_data* arg=(struct worker_data*)_arg; 

	while(1){
		//ready to work
		pthread_cond_signal(&arg->done);
		pthread_mutex_lock(&arg->work_mutex);

printf("Worker waiting\n");
		//expection command to work
		pthread_cond_wait(&arg->work, &arg->work_mutex);
printf("Worker waiting done\n");		
		arg->out = matrix_summ (arg->in1, arg->in2);
		
		pthread_mutex_unlock(&arg->work_mutex);

		}

	pthread_cond_signal(&arg->done);

	return 0;
}

int main(){
	worker_data arg;

	pthread_cond_init(&arg.work, NULL);
	pthread_mutex_init(&arg.work_mutex, NULL);
	pthread_cond_init(&arg.done, NULL);
	pthread_mutex_init(&arg.done_mutex, NULL);

	pthread_t tidy;
	pthread_create (&tidy, NULL, worker, (void *)&arg);


	arg.in1 = matrix_init (3,3);
	arg.in2 = matrix_init (3,3);	
	for(int i=0; i < matrix_get_rows(arg.in1); i++){
		for (int j=0; j < matrix_get_columns(arg.in1); j++){
			set(arg.in1, i, j, 1);
		}
	}

	//it has to be special (1) matrix
	matrix_null (arg.in2);
	int n = matrix_get_rows(arg.in2);
	if (matrix_get_columns(arg.in2) < n ) 
		n = matrix_get_columns(arg.in2);

	for(int i=0; i < n; i++){
		set(arg.in2, i, i, 1);
	}


	while (1){

		


	//	matrix_print(arg.in1);


		pthread_mutex_lock(&arg.done_mutex);
write(2, "Main waiting\n", 13);
		pthread_cond_wait(&arg.done, &arg.done_mutex);

		pthread_mutex_unlock(&arg.done_mutex);
printf("Main waiting done\n");
		pthread_cond_signal(&arg.work);

		pthread_mutex_lock(&arg.done_mutex);
		pthread_cond_wait(&arg.done, &arg.done_mutex);
		pthread_mutex_unlock(&arg.done_mutex);

		matrix_print(arg.out);
		//release first matrix (in1)
		matrix_free(arg.in1);
		
		arg.in1 = arg.out;
		
		
	}

	pthread_join (tidy, NULL);
	matrix_print (arg.out);

	matrix_free (arg.in1);
	matrix_free (arg.in2);
	matrix_free (arg.out);

	pthread_cond_destroy(&arg.work);
	pthread_mutex_destroy(&arg.work_mutex);
	pthread_cond_destroy(&arg.done);
	pthread_mutex_destroy(&arg.done_mutex);


	return 0;


}