Visual C++ - Multithreading Synchronization - Events - CEvent, CSingleLock, WaitForSingleObject
Multithreading are very interesting part of programming languages. Visual C++ offers many ways to support multithreading. You can create thread easily using _beginthread function.
if a thread is depending on the task completion of other thread and so on, then events are used to synchronize the program flow. MFC classes CEvent and CSingleLock are used for events synchronization.
Source Code
#include <afx.h>
#include <afxwin.h>
#include <afxext.h>
#include <atlbase.h>
#include <atlstr.h>
#include <afxmt.h>
#include <iostream>
#include <vector>
#include <process.h>
CEvent eventA(TRUE, TRUE, _T("EventA"));
CEvent eventB(TRUE, TRUE, _T("EventB"));
CEvent eventC(TRUE, TRUE, _T("EventC"));
CSingleLock lockA(&eventA, FALSE);
CSingleLock lockB(&eventB, TRUE);
CSingleLock lockC(&eventC, TRUE);
static void msf1(void *p)
{
const char *str = reinterpret_cast<const char*>(p);
for(int i = 0; i < 10; i++)
{
while(lockA.IsLocked() == true);
lockA.Lock();
std::cout << str << "\n";
lockB.Unlock();
}
}
static void msf2(void *p)
{
const char *str = reinterpret_cast<const char*>(p);
for(int i = 0; i < 10; i++)
{
while(lockB.IsLocked() == true);
lockB.Lock();
std::cout << str << "\n";
lockC.Unlock();
}
}
static void msf3(void *p)
{
const char *str = reinterpret_cast<const char*>(p);
for(int i = 0; i < 10; i++)
{
while(lockC.IsLocked() == true);
lockC.Lock();
std::cout << str << "\n";
lockA.Unlock();
}
}
CWinApp theApp;
using namespace std;
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
// initialize MFC and print and error on failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
_tprintf(_T("Fatal Error: MFC initialization failed\n"));
nRetCode = 1;
}
else
{
HANDLE h1 = (HANDLE) ::_beginthread(msf1, 0, "111");
HANDLE h2 = (HANDLE) ::_beginthread(msf2, 0, "222");
HANDLE h3 = (HANDLE) ::_beginthread(msf3, 0, "333");
WaitForSingleObject(h1, INFINITE);
WaitForSingleObject(h2, INFINITE);
WaitForSingleObject(h3, INFINITE);
}
return nRetCode;
}
Click here to download the VS2005 project and executable
Output
111
222
333
111
222
333
111
222
333
111
222
333
111
222
333
111
222
333
111
222
333
111
222
333
111
222
333
111
222
333
|