my purpose in the following code is adding 2 dimensional matrix elements by a single process and by a multi threaded program.Since pthread_create() function takes only 4 parameter,I want to send two parameters by encapsulating in a structure.But I can not send it rightly.Please help me,what can I do in this code?
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <pthread.h>
#include <malloc.h>
void *addition (void *ptr);
struct numbers {
int num1,num2;
};
pthread_mutex_t mymutex=PTHREAD_MUTEX_INITIALIZER;
main() {
int matrix_1[10][10];
int matrix_2[10][10];
int matrix_3[10][10];
int iret[10][10];
int i,j;
struct numbers num[10][10];
struct numbers *ptr;
ptr= (struct numbers *) malloc (sizeof(struct numbers));
ptr=num;
srand(time(NULL));
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
{
matrix_1[i][j]=rand()%100;
}
}
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
{
matrix_2[i][j]=rand()%100;
}
}
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
{
matrix_3[i][j]=matrix_1[i][j]+matrix_2[i][j];
}
}
pthread_t thread[100];
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
{
iret[i][j] = pthread_create( &thread[i][j], NULL ,addition,(void)ptr[i][j]);
if ( iret[i][j]!=0 ) {
printf("error creating thread.");
abort();
}
pthread_join( thread[i][j], NULL);
if ( pthread_join ( thread[i][j], NULL ) ) {
printf("error joining thread.");
abort();
}
}
exit(0);
}
void *addition (void *ptr)
{
int i,j;
int matrix_toplam[10][10];
struct numbers *my_ptr;
my_ptr = (struct numbers *)malloc (sizeof(struct numbers));
my_ptr=(struct numbers *)ptr;
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
{
pthread_mutex_lock(&mymutex);
matrix_toplam[i][j]=my_ptr[i][j]->num1 + my_ptr[i][j]->num2;
pthread_mutex_unlock(&mymutex);
}
}
}
Take a look on your line
The 4th parameter should be
void*according the manual, not(void). You also need a adress of the item which could be easily done by adding&toptr[i][j]Your code would need to clean, thefore there is my simplified version of what you need: