2

I'm trying out Multi-threading in C for the first time, and I seem to be doing something wrong which I hope you could help me with. Here is my code:

#include "stdafx.h"

#define MAX_THREADS 2


int a[100000];
int b[200000];

void startThreads();

DWORD WINAPI populateArrayA(LPVOID data)
{
    int i;
    int* pA = (int*)data;

    for(i = 0; i < sizeof(a) / sizeof(int); i++)
    {
        *pA = i;
        pA++;
    }

    return 0;
}
DWORD WINAPI populateArrayB(LPVOID data)
{
    int i;
    int* pB = (int*)data;

    for(i = 0; i < sizeof(b) / sizeof(int); i++)
    {
        *pB = i;
        pB++;
    }
    return 0;
}

void startThreads()
{
    HANDLE threads[MAX_THREADS];
    DWORD  threadIDs[MAX_THREADS];

    threads[0] = CreateThread(NULL,0,populateArrayA,a,0,&threadIDs[0]);
    threads[1] = CreateThread(NULL,0,populateArrayB,b,0,&threadIDs[1]);

    if(threads[0] && threads[1])
    {
        printf("Threads Created. (IDs %d and %d)",threadIDs[0],threadIDs[1]);
    }

    WaitForMultipleObjects(MAX_THREADS,threads,true,0);

}

int main(int argc, char* argv[])
{
    int i;

    memset(a,0,sizeof(a));
    memset(b,0,sizeof(b));

    startThreads();

    return 0;
}

In this code, Array "b" seems to populate fine, however Array "a" does not. Sorry if the answer is something stupid!

EDIT: I just tried again, and both arrays are all '0's. Not quite sure what's going on. I'm using Visual Studio in case it's a debugging issue or something.

Cheers.

9
  • So what does a end up looking like? Commented Jan 31, 2014 at 16:05
  • All '0's, as they are initialised too. Thanks Commented Jan 31, 2014 at 16:07
  • 1
    Weird. I just ran this exact code through Visual Studio 2010 and they both looked fine. Commented Jan 31, 2014 at 16:09
  • I just tried again, and both arrays are all '0's. Not quite sure what's going on. Commented Jan 31, 2014 at 16:09
  • 1
    When and how are you checking the array values? Commented Jan 31, 2014 at 16:09

1 Answer 1

4

The last parameter of WaitForMultipleObjects must be INFINITE, not 0. With 0, the function returns immediatly.

Sign up to request clarification or add additional context in comments.

1 Comment

strange that it still runs fine on my system here though. Maybe my processor is just faster and is able to finish the threads.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.