Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 218
  • Last Modified:

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;
}
0
Already_Googled
Asked:
Already_Googled
  • 5
  • 5
1 Solution
 
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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
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

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 5
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now