Simple thread question, I must be missing something obvious.

The following is a simple mfc console app I used to demonstrate threads and my problem. This app will hang after the first iteration of the first while loop which spawns threads in release mode. In debug mode it runs as expected. What I don't understand is, if I put a Sleep(0); statement in each while loop, then the program runs fine in release mode! Why do I need to put those Sleep statements in there to get the while loops to be responsive? (You can just cut and paste this into an mfc console app to test it should compile as is)

Thanks!

Code:

#include <afxwin.h>
#include <fstream>
#include <iostream>

using namespace std;

struct MYSTRUCT {
    int x;
    CString str;
};

int nNumOfActiveThreads;

CRITICAL_SECTION cs;

int main()
{
    InitializeCriticalSection(&cs);

    int nNumProcessors = 2;
    int i = nNumOfActiveThreads = 0;

    while (i < 20) {

        if (nNumOfActiveThreads < nNumProcessors) {

            cout << i << endl;

            MYSTRUCT *ms = new MYSTRUCT;
            ms->x = i;

            nNumOfActiveThreads++;

            AfxBeginThread(ThreadRegister, ms, THREAD_PRIORITY_NORMAL);

            i++;
        }

        Sleep(0); // If I take this sleep statement out, the app hangs in release mode here!
    }

    // ..wait for any 'leftover' threads to complete.
    while (nNumOfActiveThreads != 0) {
        Sleep(0); // If I take this sleep statement out, the app hangs in release mode here!
    }

    DeleteCriticalSection(&cs);

    system("pause");
    return 0;
}

UINT ThreadRegister(LPVOID pParam)
{
    MYSTRUCT *ms = (MYSTRUCT*)pParam;

    // Long processing task...
    Sleep(400);

    delete ms;

    EnterCriticalSection(&cs);
    nNumOfActiveThreads--;
    LeaveCriticalSection(&cs);

    return 0;
}
Already_GoogledAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

AlexFMCommented:
Why this program hangs in Release mode - it is possible to say reading Assembly code produced by compiler. For example, loop
while (nNumOfActiveThreads != 0) {
}

is possibly removed from the code as result of compiler optimizations. In this case main thread deletes critical section, and worker threads try to enter it.

Anyway, right method to wait for worker threads is using WaitForMultipleObjects. Replace AfxBeginThread with _beginthreadex, keep thread handle returned by this function is array and wait for this array in the end of the function.
0
Already_GoogledAuthor Commented:
I realize why this code will fail, I never put a critical section calls in the main thread. If I enclose the main thread with the critical section calls, it works fine.

I've looked at WaitForMultipleObjects(), but doesn't that require me to launch all my threads at once - I have over 400 threads that will need to be launched, won't that be burdening the system too much? Why is WaitForMultipleObjects() any better than what I currently have?
0
AlexFMCommented:
>> I've looked at WaitForMultipleObjects(), but doesn't that require me to launch all my threads at once.

I don't understand this. You are talking about a way to wait for all threads termination. Number of threads is defined according to your task, and not by the way you stop them.

>> Why is WaitForMultipleObjects() any better than what I currently have?

while (nNumOfActiveThreads != 0)

This loop is running in the main thread, consuming processor resources. Using wait function sets main thread to sleeping state, it wakes up only when wait condition is TRUE.
Pseude-code, your way:
Run in the loop while at least one worker thread is active.
Using wait function:
Sleep while at least one worker thread is active.

Using wait function doesn't require critical section.

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

Already_GoogledAuthor Commented:
I see what you mean Alex, I will restructure it in this way, thanks for the pointers.
0
Already_GoogledAuthor Commented:
Hi Alex,

I rewrote the sample using a semaphore and the waitforobjects() methods, if possible, could you give it a look and see if this technique is 'proper'. It compiles and runs fine, just want to know if it follows any standards.


DWORD WINAPI ThreadFunction(LPVOID pParam);

struct MYSTRUCT {
    int x;
};


#define NUM_PROCESSORS 3
#define NUM_THREADS_TO_PROCESS 20

HANDLE hSemaphore;

int main()
{
    hSemaphore = CreateSemaphore(NULL, NUM_PROCESSORS, NUM_PROCESSORS, NULL);
    HANDLE *hThreads = new HANDLE[NUM_THREADS_TO_PROCESS];

    // Try to enter the semaphore gate.
    for (int i = 0; i < NUM_THREADS_TO_PROCESS; i++) {

        // Ok to launch another thread:
        if (WaitForSingleObject(hSemaphore, INFINITE) == WAIT_OBJECT_0) {

            MYSTRUCT *ms = new MYSTRUCT;
            cout << "Launching thread with id " << i << " now." << endl;

            hThreads[i] = CreateThread(NULL, NULL, &ThreadFunction, ms, NULL, NULL);
        }
    }

    // Wait for the last threads to finish.. not sure if this is an efficient way to do it.
    WaitForMultipleObjects(NUM_THREADS_TO_PROCESS, hThreads, TRUE, INFINITE);

    CloseHandle(hSemaphore);
    delete [] hThreads;

    cout << "Done and done." << endl;
    system("pause");
    return 0;
}

DWORD WINAPI ThreadFunction(LPVOID pParam)
{
    MYSTRUCT *ms = (MYSTRUCT*)pParam;

    Sleep(1500);

    delete ms;

    ReleaseSemaphore(hSemaphore, 1, NULL);

    return 0;
}
0
AlexFMCommented:
Looks OK, but it's better to use _beginthreadex instead of CreateThread (see details in Jeffrey Richter's "Programming Applications for Microsoft Windows").
WaitForMultipleObjects is most efficient way to wait for threads to finish.
Why do you need semaphore here ??
0
AlexFMCommented:
OK, I understand what you mean using semaphore.
0
Already_GoogledAuthor Commented:
Thanks Alex. You mentioned "Programming Applications for Microsoft Windows", would you recommend it for an in depth discussion of win32 threads? I would really like to get a book on the subject.
0
AlexFMCommented:
This is the best book about Win32 programming, contains in-depth discussion of Windows memory management, threads, processes, synchronization and other topics, and a lot of perfectly written sample code. You can see details here:
http://www.amazon.com/exec/obidos/tg/detail/-/1572319968/104-4575812-6310342?v=glance
0
Already_GoogledAuthor Commented:
Thanks for all your help Alex, I appreciate it.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
System Programming

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.