Construct Thread Objects With Member Functions
Start a new thread with static/non-static member functions.
1. Introduction
According to cpprefenrence, to start a new thread with std::thread
, its constructor takes the following parameters:
Callable Object (mandatory):
The first argument must be a callable object, such as:
A function pointer (e.g., void myFunction()).
A lambda function (e.g., []() { /* code */ }
).
A pointer to a member function (e.g., &MyClass::myMethod).
A functor (an object with an overloaded operator()).
Arguments for the Callable (optional):
After the callable, you can pass additional arguments to the thread’s constructor. These arguments will be passed to the callable when the thread is started.
1 | // 1. Function Pointer |
2. Non-static Member Functions
1 |
|
Why is this passed twice?
First
this
: It binds the non-static member function (taskFunction) to the specific instance of TaskRunner. This is necessary because taskFunction is non-static and requires an instance to operate on. Withoutthis
, the thread would not know which instance of the class to invoke the function on.Second
this
: It passes the current instance (this) to the function as the argument, allowing the thread to work on that instance.
3. Static Member Functions
Passing this
twice is not necessary and we can use a static member function to avoid it. This is because static member functions are not tied to any specific object instance; they behave like regular global or free functions.
1 |
|
Static member functions can only access static data or data passed explicitly to it. Here, we pass a pointer(this
) to a TaskRunner
object (TaskRunner* runner) as its parameter. This allows the static function to access the instance-specific data or call other member functions of the TaskRunner
object. Now, we only need to pass this
once in the std::thread
constructor, as it serves as the argument for the static member function.
References
Construct Thread Objects With Member Functions
http://chuzcjoe.github.io/2025/01/27/cpp-construct-thread-with-member-functions/