0

I try to initialize the borders (north, east, south, west) of a 2d array with four pthreads. My code looks like this:

#define M 500
#define N 500
#define NUM_THREADS 4
double plate[M][N];
pthread_t threads[NUM_THREADS];

void *initBorder(void *arg) {
    int index = *((int *) arg);
    switch (index) {
        case 0:
            for (int i = 0; i < N; i++ ) { plate[0][i] = 0; }
            break;
        case 1:
            for (int i = 1; i < M-1; i++) { plate[i][N-1] = 100; }
            break;
        case 2:
            for (int i = 0; i < N; i++) { plate[M-1][i] = 100; }
            break;
        default:
            for (int i = 1; i < M-1; i++) { plate[i][0] = 100; }
            break;
    }
    return NULL;
}

int main() {
    double plate[M][N];

    for (int i = 0; i < NUM_THREADS; i++) {
        printf("Thread %d created\n", i);
        pthread_create(&threads[i], NULL, initBorder, (void *) &i);
    }

    for (int i = 0; i < NUM_THREADS; i++) {
        pthread_join(threads[i], NULL);
    }
    printf("Threads joined\n");
    printPlate();

    return 0;
}

The problem is that I only get sometimes the result that I expect (North initialized with zero, rest with value of 100). Maybe someone of you could help me.

Thank you very much.

Habebit
  • 957
  • 6
  • 23
  • `double plate[M][N];` is a global variable and a local variable in `main()`. They are different variables. Also why do you `i=1; i < M-1` and not `i=0; i < M` ? Also your code is missing `#include`s and what is the definition of `printPlate`? – KamilCuk Jun 10 '19 at 15:13
  • the `plate` variable in the `main` function isn't necessary, you are right. The complete first row should contain `zeros`, thats why there is `i=1; i < M-1` – Habebit Jun 10 '19 at 15:15
  • 1
    As all threads get the same address passed in there is a race reading the changing value it points to. – alk Jun 10 '19 at 15:17

0 Answers0