greetings,
im writing that program that creates a 2 square matrices that need to be added. but the trick is i need to use pthreads in order to do it... for soem reason my output is just 0. Any help would be appreciated im almost done im just stuck on this part.

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

int range, size;
int *A, *B, *C;

/*struct thread_param_t {
	int offset;
};*/

void IPMatrix(int *matrix, int size){
	int i,j;
	int len = size*size;
	for(i = 0; i < size; i++)
	{
		for(j = 0; j < size; j++)
		{
			*(matrix+i+j)=rand()%100+1;

			// Not being threaded, so OK here.
			printf("%3d ", (int)*(matrix+i+j));
		}
		printf("\n");
	}
	printf("\n\n");
}


void *Add(void *arg)
{
	int first, second;
	int *a=A, *b=B,*c=C;
	int* blah=(int*)arg;
        int third=*blah;
        //int adding=(int*)third+range;
        //struct thread_param_t *params = (struct thread_param_t *)(arg);
	//int start = params->offset;
	//c += start;
	for(first = third; first < third+range ; first++)
	{
		for(second = 0; second < size; second++)
		{
	           *c=*a+*b;	
                         
		}
	}

	pthread_exit(0);
}


main(int argc, char* argv[])
{
	int threads = 5;
	int x;
	int endresult;
	int startingIndex[threads];
	//struct thread_param_t thread_params[numThreads];
	pthread_t hThread[threads];
	startingIndex[0] = 0;
	
	if(argc < 2) {
		printf("Usage: %s size\n", argv[0]);
		return 1;
	}
	size = atoi(argv[1]);
	range = size / threads;
	A = (int*)calloc(size*size, sizeof(int));
	B = (int*)calloc(size*size, sizeof(int));
	C = (int*)calloc(size*size, sizeof(int));
	IPMatrix(A, size);
	IPMatrix(B, size);
	//memset(C, 0, size*size*sizeof(int));
       for(x = 1; x < threads; x++)
	{
		startingIndex[x] = startingIndex[x - 1] + range;
	}
	for(x = 0; x < threads; x++)
	{
		endresult = pthread_create(&hThread[x], NULL, Add, &startingIndex[x]);
	}
	for(x = 0; x < threads; x++)
	{
		pthread_join(hThread[x], NULL);
	}
       int y=0;
        for (x=0; x<size; x++){
         for (y=0; y<size; y++){
             printf("%3d ", (int)*(C+x+y));
             }
            printf("\n");
        }
	//free(A);
	//free(B);

	return 0;

}

Recommended Answers

All 3 Replies

first of all,u should add seed of random data

void srand( unsigned int seed );

use current time as seed!

okay thank you any other suggestions......please??

How about first doing it single-threaded and then moving up?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.