Synchronous and Asynchronous calls in C++

Sometimes there can be confusion between Synchronous and Asynchronous calls. A synchronous call is the one in which the function/call/procedure has to return before the next statement can be executed. What this means is that the function is blocking the rest of the code.

In asynchronous calling, generally there would be multiple threads. So a function call on one thread will probably not block the function call on other thread. That means that both the functions are asynchronous.

Here is a simple example that I have modified from an earlier example to show synchronous and asynchronous calling:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Example from http://www.adrianxw.dk/SoftwareSite/Threads/Threads2.html
//This shows an example of Synchronous and Asynchronous function calls
#include <windows.h>
#include <process.h>
#include <iostream>
using namespace std;

void
Func1(void *);
void
Func2(void *);

CRITICAL_SECTION Section; //This will act as Mutex


int
main()
{

InitializeCriticalSection(&Section);

//Synchronous calling
cout<<"\nSynchronous calling"<<endl;
Func1(0);
Func2(0);

//Asynchronous calling
cout<<"\nAsynchronous calling"<<endl;
HANDLE hThreads[2];

//Create two threads and start them
hThreads[0] = (HANDLE)_beginthread(Func1, 0, NULL);
hThreads[1] = (HANDLE)_beginthread(Func2, 0, NULL);

//Makes sure that both the threads have finished before going further
WaitForMultipleObjects(2, hThreads, TRUE, INFINITE);

//This is done after all threads have finished processing
DeleteCriticalSection(&Section);

cout << "Main exit" << endl;
return
0;
}


void
Func1(void *P)
{

int
Count;

for
(Count = 1; Count < 11; Count++)
{

EnterCriticalSection(&Section);
cout << "Func1 loop " << Count << endl;
LeaveCriticalSection(&Section);
Sleep(1000);
}

return
;
}


void
Func2(void *P)
{

int
Count;

for
(Count = 10; Count > 0; Count--)
{

EnterCriticalSection(&Section);
cout << "Func2 loop " << Count << endl;
LeaveCriticalSection(&Section);
Sleep(1000);
}

return
;
}







The output is as follows:

Check out this stream