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:

  1. The #include directive includes the necessary header files for using iostream and thread in the C++ program.

  2. The main() function is the entry point of the program.

  3. The variable x is declared and assigned a value of 10.

  4. The lambda function is created using the syntax [] (int num) { / lambda function body / }. This lambda function takes an integer parameter num and prints it to the console using std::cout.

  5. The std::thread class is used to create a new thread. The constructor of std::thread takes the lambda function (lambda_func) as a parameter, along with the argument x.

  6. The join() function is called on the my_thread object to ensure that the main thread waits for the new thread to complete its execution before terminating.

  7. The return 0; statement ends the main() 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++.