c++ lambda thread example
Here is an example of a C++ program that demonstrates the usage of lambda functions with threads:
#include <iostream>
#include <thread>
int main() {
int x = 10;
// Create a lambda function that takes an integer as a parameter
auto lambda_func = [](int num) {
std::cout << "Inside lambda function. Number: " << num << std::endl;
};
// Create a thread and pass the lambda function as a parameter
std::thread my_thread(lambda_func, x);
// Join the thread to the main thread
my_thread.join();
return 0;
}
Explanation:
The
#include
directive includes the necessary header files for usingiostream
andthread
in the C++ program.The
main()
function is the entry point of the program.The variable
x
is declared and assigned a value of 10.The lambda function is created using the syntax
[] (int num) { / lambda function body / }
. This lambda function takes an integer parameternum
and prints it to the console usingstd::cout
.The
std::thread
class is used to create a new thread. The constructor ofstd::thread
takes the lambda function (lambda_func
) as a parameter, along with the argumentx
.The
join()
function is called on themy_thread
object to ensure that the main thread waits for the new thread to complete its execution before terminating.The
return 0;
statement ends themain()
function and the program.
Please note that the lambda function can be customized to perform any desired task, and the example provided here is just a simple demonstration of using lambda functions with threads in C++.