-1

For each cell, I want to create a thread that will multiply its current row number by its current column number. The problem is that I don't know how to properly dereference the matrix and use it. Valgrind says that there is an uninitialized value of size 8 used in fillcell. Since it's size 8 I suspect it is the pointer. How can I properly convert it?

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

#include "myutils.h"
int i = 10;
int j = 10;

int var = 0;
int w,x;


void * fillcell(void * param){

    int** value = (int**) param;

    value[x][w]= x*w;

    printf("%d \n",w*x);


}


int main(int argc, char * argv[])
{
    pthread_t * tid;
    tid = malloc(i*j*sizeof(pthread_t));
    
    int A[i][j];

    for ( x = 0; x < i; x++){
        for( w = 0; w < j; w++){
            
            pthread_create(&tid[var],NULL , fillcell,&A);
            pthread_join(tid[var],NULL);  
            var++:
        }
    }

    free(tid);
}
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • You should absolutely read some [pthread tutorial](https://computing.llnl.gov/tutorials/pthreads/) – Basile Starynkevitch Feb 14 '18 at 17:46
  • Possible duplicate of [Create a pointer to two-dimensional array](https://stackoverflow.com/questions/1052818/create-a-pointer-to-two-dimensional-array) – Tsyvarev Feb 15 '18 at 10:27

1 Answers1

2
int i = 10;
int j = 10;

int var = 0;
int w,x;

Globals: just say no.

They're not generally a great idea in single-threaded programs, but using mutable globals (which start off uninitialized) in multiple threads is ... risky.

void * fillcell(void * param) {
    int** value = (int**) param;
    value[x][w]= x*w;

your program has a single variable x, and a single variable w. They're shared between all threads. Creating a thread doesn't create a snapshot of all global variables for the new thread's use, they're all just shared. There is absolutely no way to know, in this program, what values of x and w a given thread will see in this function.

You can fix this by passing an explicit {x, w, A} parameter structure to each thread - and I mean a different instance of that structure for each thread.

Finally, int A[10][10] is not an int**, and it doesn't decay to one. To prove this, just print the address of each A[x][w] and then print the address of each value[x][w]. See how your 2D array is really laid out. Printing all your addresses will also make it easy to understand the address valgrind is complaining about.

Useless
  • 64,155
  • 6
  • 88
  • 132