Amirreza H
Amirreza H

Reputation: 63

How may i use asynchronous functions in C++?

I'm a beginner C++ programmer. As i know statements will be executed line by line so if i call a function inside main,the body of called function will be executed first then the rest of the code...

As shown in following code:

int main()
{
 ABC();
 // ...
}

void ABC()
{
// ...
}

So execution of my current program is synchronous,but i want it to be asynchronous.

Sorry for bad title! I couldn't find better title for the question! If you can plz edit it.

Thanks for your help to a beginner programmer like me :D

Upvotes: 1

Views: 2592

Answers (2)

Programmer
Programmer

Reputation: 125455

Provide examples instead of pointing the beginner to a long article. The article or link provided may go offline anytime therefore leading to people to ask the same question again.

Async is not usually for beginners but since you want to learn it, here is an example of how to do it. You can just copy the code and paste it then run it. Study the code. They are commented very well for you to understand. See which one works best for you.

Method 1: Requires C++ 11

Should work on Windows, Mac and Linux*

 #include <iostream>
    #include <future> //Import the asynchronous Library

    using namespace std;

    //The function you want to call asynchronously
    void ABC()
    {
    cout<<"Hello From ABC Function"<<endl;
    }

    int main()
    {
        /*Setup **ABC function**, We will call it **MyABCFunction**, but you can call it anything else.
       Inside MyABCFunction, we call **sync function** and pass it the name of the **function** we want
        to call which is "ABC()". You don't include the "()", just the name "ABC".*/

      future<void> MyABCFunction(async(ABC));

      //Call ABC function
      MyABCFunction.get();


      //Show message from the Main Function
      cout << "Hello From Main Function." <<endl;
      return 0;
    }

Since you are new to C++, I will mentioned that you should't be using "using namespace std" as it can lead to program getting bigger and other naming conflicts.

Let's fix it below:

    #include <iostream>
    #include <future> //Import the asynchronous Library

    /*No "using namespace std". Instead, each c++ library function must be begin with "std::"
    which includes Standard library for the function needed
    */

    //The function you want to call asynchronously
    void ABC()
    {
        //std:: before cout and endl
       std::cout<<"Hello From ABC Function"<<std::endl;
    }

    int main()
    {
      //std:: before future and async
      std::future<void> MyABCFunction(std::async(ABC));

      //Call ABC function
      MyABCFunction.get();

      //std:: before cout and endl
      std::cout << "Hello From Main Function." <<std::endl;
      return 0;
    }

Method 2:

C++ 11 NOT required

Works on Windows ONLY (Easiest and shortest way of doing it)

#include <iostream> //For text on screen
#include <windows.h>  //Must include the use HANDLE class
#include <process.h>   // needed for _beginthread()

//Function prototype of ABCD function to be called in a thread.
void ABCD(void *param);

int main()
{


    int val = 0;
    HANDLE handle; //Create a handle (Only on Windows OS)

    /*Initialize the handle and begin thread. */
    /*_beginthread takes the name of the function to be called "ABCD" */
    /*_beginthread takes the stack size of the thread 0*/
    /*_beginthread takes the parameter to be passed to the "ABCD" which is 0(val) since void ABCD(void *param) takes void which means no parameter*/

    handle = (HANDLE) _beginthread( ABCD,0,&val);

 /*Do infinite loop on the main function to prove that main and ABCD function are running at the same time*/
    while(1)
    {
        std::cout<<"thread from main function"<<std::endl;
    }

    //Wait for ACBD to finish before exiting the program
    WaitForSingleObject(handle,INFINITE);
    return 0;
}

//ABCD function to be called from the thread
void ABCD(void *param)
{
    /*Do infinite loop on the main function to prove that ABCD and main function are running at the same time*/
    while(1)
    {
        std::cout<<"thread from ABCD function"<<std::endl;
    }
    _endthread(); // End thread. Won't be called since we are looping forever in while(1) loop

}

For more information about _beginthread

Method 3:

C++ 11 NOT required

POSIX standard works on Windows, Mac and Linux

We will be counting from 1 t0 10,000 in the ABCD function while counting 1 to 5,000 in the main function.

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>

void *ABCD(void *arg)
{

    //count from 1 to 10000 from the ABCD function thread
    for(int i=1; i<=10000;i++)
    {
        std::cout<<"thread from ABCD function "<<i<<std::endl;
    }
}

int main()
{

    pthread_t myPthread;

    //Create and call the ABCD function to start counting
    pthread_create(&myPthread, NULL, ABCD, NULL);

    //count from 1 to 5,000 from the main function thread
    for(int i=1; i<=5000;i++){
        std::cout<<"thread from main function"<<std::endl;
    }
}

The problem here is that the main function will finish counting first because it counts up to 5,000 while main function counts to 10,000. When the main function finishes first, it terminates the whole program even when the ABCD fucntion is NOT done counting. To solve this problem, we use pthread_join fucntion to wait for the ABCD function to finish before our program can terminate.

Below is the whole code:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>

void *ABCD(void *arg)
{

    //count from 1 to 10000 on from ABCD function thread
    for(int i=1; i<=10000; i++)
    {
        std::cout<<"thread from ABCD function "<<i<<std::endl;
    }
}

int main()
{

    pthread_t myPthread;

    //Create and call the ABCD function to start counting
    pthread_create(&myPthread, NULL, ABCD, NULL);

    //count from 1 to 5,000 on from the main function thread
    for(int i=1; i<=5000; i++)
    {
        std::cout<<"thread from main function"<<std::endl;
    }

    //Wait for ABCD function to finish before we exit
    int a =0;
    pthread_join(myPthread, (void **)&a);
}

I hope this can helps all the c++ thread beginners out there. I suggest you lean about semaphore once you understand the basic of Method 3 I provided. For more information about pthread_t

Upvotes: 3

paulsm4
paulsm4

Reputation: 121849

If you're using C++ 11, you might consider std::async:

Otherwise, you can easily:

  • Create a thread

  • Set a timer

Upvotes: 3

Related Questions