Software & Finance





Visual C++ - Multithreading Synchronization - Events - CreateEvent, SetEvent, 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.

 


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>

 

HANDLE hEventA = ::CreateEvent(NULL, TRUE, FALSE,  _T("TestEventA"));

HANDLE hEventB = ::CreateEvent(NULL, TRUE, FALSE,  _T("TestEventB"));

HANDLE hEventC = ::CreateEvent(NULL, TRUE, TRUE, _T("TestEventC"));

 

static void f1(void *p)

{

    const char *str = reinterpret_cast<const char*>(p);   

 

    for(int i = 0; i < 10; i++)

    {

        ::WaitForSingleObject(hEventC, INFINITE);

        ::ResetEvent(hEventC);

        std::cout << str << "\n";

        ::SetEvent(hEventA); // Give Up Control A to B

    }

}

 

static void f2(void *p)

{

    const char *str = reinterpret_cast<const char*>(p);   

 

    for(int i = 0; i < 10; i++)

    {

        ::WaitForSingleObject(hEventA, INFINITE);

        ::ResetEvent(hEventA);

        std::cout << str << "\n";

        ::SetEvent(hEventB); // Give Up Control B to C

    }

}

 

static void f3(void *p)

{

    const char *str = reinterpret_cast<const char*>(p);   

 

    for(int i = 0; i < 10; i++)

    {

        ::WaitForSingleObject(hEventB, INFINITE);

        ::ResetEvent(hEventB);

        std::cout << str << "\n";

        ::SetEvent(hEventC); // Give Up Control C to A

    }

}

 

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 h3 = (HANDLE) ::_beginthread(f3, 0, "CCC");

        HANDLE h2 = (HANDLE) ::_beginthread(f2, 0, "BBB");

           HANDLE h1 = (HANDLE) ::_beginthread(f1, 0, "AAA");

 

        WaitForSingleObject(h1, INFINITE);

        WaitForSingleObject(h2, INFINITE);

        WaitForSingleObject(h3, INFINITE);

       } 

       return nRetCode;

}

 

Click here to download the VS2005 project and executable

 

Output


 

AAA
BBB
CCC
AAA
BBB
CCC
AAA
BBB
CCC
AAA
BBB
CCC
AAA
BBB
CCC
AAA
BBB
CCC
AAA
BBB
CCC
AAA
BBB
CCC
AAA
BBB
CCC