C++ start thread – C++11 : Start thread by member function with arguments

C++ start thread: In the previous article, we have discussed about C++ : How to copy / clone a STL List or Sub List. Let us learn how to Start thread by member function with arguments in C++ Program.

Starting thread by member function with arguments

C++11 thread: We are going to see how to start threads by member function with arguments .

Starting thread with non static member function :

C++ thread class: We will be using the following class to demonstrate .

class Example
{
public:
    void exec(std::string command);
};

Class Example contains a non static member function Exec( ) .

We will now have to create an object of the class to call the function so that we can start it as thread function.

Now, to create the thread to run the function.

Example *ExamplePtr = new Example();
std::thread th(&Example::exec, ExamplePtr, "Example");

Here we have passed three arguments,

  1. &Example::exec – A pointer pointing to the member function. This will be used as the thread function.
  2.  ExamplePtr – This is a pointer pointing to the object of the class with which the above function is to be called. Every non -static member function’s first argument is the pointer to its class. Hence this will be passed as the first argument into the function by the thread class.
  3. “Example” – This is the string value. It is passed as second argument to the member function.

CODE:-

#include <iostream>
#include <thread>

class Example
{
public:
    void exec(std::string command)
    {
        for (int i = 0; i < 5; i++)
        {
            std::cout << command << " :: " << i << std::endl;
        }
    }
};
int main()
{
    //Creatig object
    Example *ExamplePtr = new Example();

    //Creatig thread
    std::thread th(&Example::exec, ExamplePtr, "Example");
    th.join();

    delete ExamplePtr;
    return 0;
}
Output :
Example :: 0
Example :: 1
Example :: 2
Example :: 3
Example :: 4

Starting thread with static member function :

We can call static member functions directly without requiring an object.

CODE:-

#include <iostream>
#include <thread>

class Example
{
public:
    static void exec(std::string command)
    {
        for (int i = 0; i < 5; i++)
        {
            std::cout << command << " :: " << i << std::endl;
        }
    }
};
int main()
{
    //Creatig thread
    std::thread th(&Example::exec, "Example");
    th.join();

    return 0;
}
Output :
Example :: 0
Example :: 1
Example :: 2
Example :: 3
Example :: 4

Answer these:

  1. C thread member function with arguments?
  2. C thread function with arguments?
  3. C thread as class member?
  4. C thread member function with arguments?
  5. C++ thread function with arguments?
  6. C++ thread as class member?
  7. Call function in another thread c++?
  8. C++ thread access member variable?
  9. C thread non static member function?