Launching Thread Using Non-Static Member Function

We can also launch the thread using the non-static member function of a class. The following snippet demonstrates how to do it.

C++




// defining clasc
class Base {
public:
    // non-static member function
    void foo(param) { Statements; }
}
 
// object of Base Class
Base b;
 
// first parameter is the reference to the functionn
// and second paramter is reference of the object
// at last we have arguments
std::thread thread_obj(&Base::foo, &b, params);


Multithreading in C++

Multithreading is a feature that allows concurrent execution of two or more parts of a program for maximum utilization of the CPU. Each part of such a program is called a thread. So, threads are lightweight processes within a process.

Multithreading support was introduced in C++11. Prior to C++11, we had to use POSIX threads or <pthreads> library. While this library did the job the lack of any standard language-provided feature set caused serious portability issues. C++ 11 did away with all that and gave us std::thread. The thread classes and related functions are defined in the <thread> header file.

Syntax:

std::thread thread_object (callable);

std::thread is the thread class that represents a single thread in C++. To start a thread we simply need to create a new thread object and pass the executing code to be called (i.e, a callable object) into the constructor of the object. Once the object is created a new thread is launched which will execute the code specified in callable. A callable can be any of the five:

  • A Function Pointer
  • A Lambda Expression
  • A Function Object
  • Non-Static Member Function
  • Static Member Function

After defining the callable, we pass it to the constructor.

Similar Reads

Launching Thread Using Function Pointer

A function pointer can be a callable object to pass to the std::thread constructor for initializing a thread. The following code snippet demonstrates how it is done....

Launching Thread Using Lambda Expression

...

Launching Thread Using Function Objects

std::thread object can also be launched using a lambda expression as a callable. The following code snippet demonstrates how this is done:...

Launching Thread Using Non-Static Member Function

...

Launching Thread Using Static Member Function

Function Objects or Functors can also be used for launching a thread in C++. The following code snippet demonstrates how it is done:...

Waiting for threads to finish

...

Contact Us