Armine Harutyunyan
Armine Harutyunyan

Reputation: 3

Working with threads in c++

I need to create two threads, one of which will return even numbers and the other will return odd numbers. What am I doing wrong?

here is my console

Here is a screenshot of my functions

int _tmain(int argc, _TCHAR* argv[])
{
    DWORD ID1 = 1, ID2 = 100;
    DWORD arr[] = {ID1, ID2};
    HANDLE h[1];
    for (int i = 0; i < 2; ++i)
    {
        h[0] = CreateThread(NULL, 0, &f1, arr, 0, &arr[0]);
        if (h[0] == NULL)
            _tprintf(_T("%d"), GetLastError());
        h[1] = CreateThread(NULL, 0, &f2, arr, 0, &arr[1]);
        if (h[1] == NULL)
            _tprintf(_T("%d"), GetLastError());
    }

    WaitForMultipleObjects(2, h, TRUE, INFINITE);

    for (int i = 0; i < 2; ++i)
        CloseHandle(h[i]);

    return 0;
}

Upvotes: 0

Views: 137

Answers (1)

C. Korb
C. Korb

Reputation: 307

Change this

HANDLE h[1];
for (int i = 0; i < 2; ++i)
{
    h[0] = CreateThread(NULL, 0, &f1, arr, 0, &arr[0]);
    if (h[0] == NULL)
        _tprintf(_T("%d"), GetLastError());
    h[1] = CreateThread(NULL, 0, &f2, arr, 0, &arr[1]);
    if (h[1] == NULL)
        _tprintf(_T("%d"), GetLastError());
}

To this

HANDLE h[2];
h[0] = CreateThread(NULL, 0, &f1, arr, 0, &arr[0]);
if (h[0] == NULL)
    _tprintf(_T("%d"), GetLastError());
h[1] = CreateThread(NULL, 0, &f2, arr, 0, &arr[1]);
if (h[1] == NULL)
    _tprintf(_T("%d"), GetLastError());
  • You are creating 2 threads within the body of a for loop which executes twice (AKA 4 threads when you really meant for 2).
  • You are attempting to save the handles to these threads into a HANDLE array which can only hold one element.
  • On the second execution of the loop, you have overwritten the elements of h[] again, so when you later wait for them to finish and attempt to close the handles, you are not even closing the same handle.
  • You need the HANDLE array to be size 2, and you need to remove the first for loop (you are passing the function pointers separately, so there is no way to do this in a loop unless you put the function pointers into an array of the same length as h[]).

Upvotes: 3

Related Questions