User Tools

Site Tools


c:c_threads:create_a_thread:create_a_thread_with_a_lambda

C - C++ Threads - Create a thread - Create a thread with a lambda

#include <iostream>
#include <thread>
 
int main()
{
  std::thread t1([] {
    std::cout << "Hello World" << std::endl;
  });
  t1.join();
  return 0;
}

Using a lambda closure

A lambda closure is nothing but a variable storing a lambda expression.

You can store a lambda in a closure if you intend to reuse the lambda expression at more than one place in your code.

#include <iostream>
#include <thread>
 
int main()
{
  // Define a lambda closure.
  auto HelloWorldFunc = []() -> void { std::cout << "Hello World" << std::endl; };
  std::thread t1(HelloWorldFunc);
  t1.join();
  return 0;
}

With Arguments

auto HelloWorldFunc = [](std::string name, int age) -> void { std::cout << "Hello " << name << ".  You are " << age << " years old." << std::endl; };
std::thread t1(HelloWorldFunc, "Peter", 21);
t1.join();
c/c_threads/create_a_thread/create_a_thread_with_a_lambda.txt · Last modified: 2021/03/05 09:53 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki