User Tools

Site Tools


c:c_threads:create_a_thread:create_a_thread_with_a_lambda

This is an old revision of the document!


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

#include <thread>
#include <iostream>
 
using namespace std;
 
int main()
{
  thread t1([] {
    cout << "Launching Scud missile" << 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 <thread>
#include <iostream>
 
using namespace std;
 
int main()
{
  // Define a lambda closure
  auto LaunchMissileFunc = []() -> void { cout << "Launching Cruiser Missile" << endl; };
  thread t1(LaunchMissileFunc);
  t1.join();
  return 0;
}
c/c_threads/create_a_thread/create_a_thread_with_a_lambda.1614909491.txt.gz · Last modified: 2021/03/05 01:58 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki