Table of Contents

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();