Eng.Fouad
Eng.Fouad

Reputation: 117579

How can I initiate an array, each element in a separate thread

I am trying to create an array of size n (where n is user's input) and when the user runs the program, the array elements should be set to 1 (each in a separate thread). Here is what I have done so far:

#include <windows.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <conio.h>
#include <process.h>

int *x;

DWORD WINAPI init_X(LPVOID param)
{
    int index = *(int *) param;
    x[index] = 1;

    return 0;
}

int main(int argc, char *argv[])
{
    int n = atoi(argv[1]);
    int i; // counter.
    HANDLE THandles[n];

    x = malloc(n * sizeof (int));

    for(i = 0; i < n; i++)
    {
        THandles[i] = CreateThread(NULL, 0, init_X, &i, 0, NULL);
    }

    // Now wait for threads to finish
    WaitForMultipleObjects(n, THandles, TRUE, INFINITE);

    // Close the thread handle
    for(i = 0; i < n; i++)
    {
        CloseHandle(THandles[i]);
    }

    printf("After initialization x = ");
    for(i = 0; i < n; i++)
    {
        printf("%d ", x[i]);
        if(i < n - 1) printf(" ");
    }

    // ...

    return 0;
}

I run this program and I got wrong outputs:

> Test.exe 3
After initialization x = 11611536 11600064 50397186

It should be After initialization x = 1 1 1 though. I am not sure how I can I fix this, but I am sure its something related to the pointers.

P.S: I'm Java programmer so I'm not familiar with pointers.

Upvotes: 0

Views: 120

Answers (2)

Necrolis
Necrolis

Reputation: 26171

The value you are passing as your array index will more than likely be invalid by the time the thread runs, as there is no guaranteeing that the thread is run immediately after the call to CreateThread.

You have two solutions, either pass by value (simple & easy, but not always safe) or allocate a temporary buffer for the value that will be freed by the thread when its used.

Minor Update:

In fact, a better way would be to pass &x[i], then you can just do *(int*)param = 1;

Upvotes: 2

K-ballo
K-ballo

Reputation: 81349

You are passing i by pointer to the thread, so the value each thread gets will depend on when int index = *(int *) param; actually executes and it should be something between 0 and n. You can just pass i by value (casted to a pointer) to avoid this.

Upvotes: 0

Related Questions