In modern C++ development we can use multi-thread operations and parallel programming features in our applications in different ways of modern programming features. The std::thread
class is a special class defined in <thread>
header in the concurrency support library that comes with C++11. We can use the std::thread
class in multi-thread operations with functor objects, and in this post, we explain how to use std::thread
with a functor object in C++.
First, let’s learn what is functor and how we can use it.
What is functor in C++?
A functor is an object that can be used as a function or function pointer, this term is not same as function term in programming. We can pass many arguments with them; thus, we don’t need to define many global variables, we can use these kinds of variables in the scope that we use. We can create operators as given simple functor example below,
1 2 3 4 5 6 7 8 9 10 |
class Ty { public: void operator()(int r) { double a = M_PI*r*r; } }; |
What is std::thread in C++?
In modern C++, a concurrency support library is designed to solve problems in multi-thread operations. This library includes built-in support for threads (std::thread
), atomic operations (std::atomic
), mutual exclusion (std::mutex
), condition variables (std::condition_variable
), and many other features.
The std::thread
class is a special class defined in <thread>
header that comes with C++11, and it allows multiple functions to execute and represents a single thread of execution concurrently. We can use the join()
method of the thread that waits for the thread to finish its execution.
Let’s see how we can use std::thread
with a functor object in C++.
Is there an example about running functor object with std::thread in C++?
Here is a std::thread
example with a functor object ().
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <thread> class Ty { public: void operator()(int r) { double a = M_PI*r*r; } }; int main() { Ty o2; std::thread myt(o2, 5); // add myf(5) to thread myt.join(); // join thread to run in threads } |
Note that, we can use lambda expressions with std::thread
which is a modern way of C++ programming.
C++ Builder is the easiest and fastest C and C++ IDE for building simple or professional applications on the Windows, MacOS, iOS & Android operating systems. It is also easy for beginners to learn with its wide range of samples, tutorials, help files, and LSP support for code. RAD Studio’s C++ Builder version comes with the award-winning VCL framework for high-performance native Windows apps and the powerful FireMonkey (FMX) framework for cross-platform UIs.
There is a free C++ Builder Community Edition for students, beginners, and startups; it can be downloaded from here. For professional developers, there are Professional, Architect, or Enterprise version.
Design. Code. Compile. Deploy.
Start Free Trial
Free C++Builder Community Edition