How to know when threads have died
i am using multithreading in my program but im unable to know when all the threads have finished their tasks ... and when they return to the main program so i can display that the program is now ready to exit or task completed ... and also how can i synchronise the threads so that i may not get any write memory exceptions
Re: How to know when threads have died
Quote:
Originally posted by Sanai
and also how can i synchronise the threads so that i may not get any write memory exceptions
Well...the question would be what you are trying to synchronize...the threads itselves or a resource which is accessed by multiple threads...
1. Synchronize threads
Code:
class CFoo
{
public:
~CFoo() { CloseHandle(m_hEvent); }
void CreateThreads()
{
// Create event
m_hEvent = CreateEvent(0, TRUE, FALSE, 0);
CreateThread(0, 0, ThreadOne, &m_hEvent, 0, 0);
CreateThread(0, 0, ThreadTwo, &m_hEvent, 0, 0);
}
private:
HANDLE m_hEvent;
static UINT ThreadOne(LPVOID Param)
{
HANDLE *pEvent = static_cast<HANDLE *>(Param);
// Wait for event
if(WaitForSingleObject(*pEvent, INFINITE) == WAIT_OBJECT_0)
{
// Thread two is done...start working
// Reset event
ResetEvent(*pEvent);
}
}
static UINT ThreadTwo(LPVOID Param)
{
HANDLE *pEvent = static_cast<HANDLE *>(Param);
// Do processing
// Set event
SetEvent(*pEvent);
}
};
Note that the above sample does not handle any error situations though....
2. Synchronize access to resource
Code:
class CSync
{
public:
CSync() { InitializeCriticalSection(&m_CriticalSection); }
~CSync() { DeleteCriticalSection(&m_CriticalSection); }
void Acquire() { EnterCriticalSection(&m_CriticalSection); }
void Release() { LeaveCriticalSection(&m_CriticalSection); }
private:
CRITICAL_SECTION m_CriticalSection; // Synchronization object
};
class CLockGuard
{
public:
CLockGuard(CSync &refSync) : m_refSync(refSync) { Lock(); }
~CLockGuard() { Unlock(); }
private:
CSync &m_refSync; // Synchronization object
CLockGuard(const CLockGuard &refcSource);
CLockGuard &operator=(const CLockGuard &refcSource);
void Lock() { m_refSync.Acquire(); }
void Unlock() { m_refSync.Release(); }
};
The above mechanism can be used as follows...
Code:
int iGlobalInt = 10;
CSync GlobalSync;
// Thread 1
CLockGuard Gate(GlobalSync);
iGlobalInt = 12;
// Thread 2
CLockGuard Gate(GlobalSync);
iGlobalInt = 22;