Matrix multiplication using threads in Ruby

Hi friends. I have been trying to multiply two matrices using threads. Each and every element of the matrix obtained after multiplication is calculated in separate threads. The problem is, while looping, more than one thread is accessing or sharing a common variable. So a deadlock situation arises. Can someone help on how to solve this problem?

1 Like

But why are you allowing different threads to share a common variable ? By default every thread has either separate copy of data area which includes variables and structures etc. I don’t know anything about Ruby, but i have a C code for the same, check it if it matches your need.

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

#define numThrds 10
#define M 3
#define N 3
#define P 3
int A[M][N];
int B[N][P];
int C[M][P];
struct node
{
int i,j;
};
void *multiply(void *args)
{

 struct node *val=(struct node *)args;
 int i,j,k;
 i=val->i;
 j=val->j;
 int sum=0;
 for(k=0;k<N;k++)
 sum+=A[i][k]*B[k][j];
 C[i][j]=sum;
 //printf("%d %d %d\n",i,j,sum);
 }
int main()
{
int i,j;
pthread_t thrd[M*P];
int error;
struct node *val=(struct node *)malloc(sizeof(struct node *));
printf("Enter a %dx%d matrix\n",M,N);
for(i=0;i<M;i++)
    for(j=0;j<N;j++)
    scanf("%d",&A[i][j]);
printf("Enter a %dx%d matrix\n",N,P);
for(i=0;i<N;i++)
    for(j=0;j<P;j++)
    scanf("%d",&B[i][j]);
 int c=0,z;
for(i=0;i<M;i++){
        for(j=0;j<P;j++)
        {
        val->i=i;
        val->j=j;
      printf("%d %d %d\n",i,j,z=pthread_create(&thrd[c],0,multiply,(void *)val));
      if(z)pthread_create(&thrd[c],0,multiply,(void *)val);
     c++;
       }
}

for(i=0;i<M*P;i++){
  if( pthread_join(thrd[i],NULL)) pthread_join(thrd[i],NULL);}
 printf("\n");
for(i=0;i<M;i++,printf("\n"))
    for(j=0;j<P;j++)
    printf("%d ",C[i][j]);
return 0;
}
//