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;
}

With Arguments

auto LaunchTorpedoFunc = [](int numCities, string torpedoType) -> void { cout << "Firing torpedo " << torpedoType << " at" << numCities << " cities." << endl; };
thread t1(LaunchTorpedoFunc, 7, "Barracuda");
t1.join();
c/c_threads/create_a_thread/create_a_thread_with_a_lambda.1614910319.txt.gz · Last modified: 2021/03/05 02:11 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki