createThread

Thread Creation

Thread creation is easy. Call  std::thread, and a new thread will be created. The thread gets a work package and starts it immediately. The creator of the thread (the Parent) has to take care of the created thread (the child). The parent should wait until their child completes their task or has to detach himself from the child. The child thread can get its payload task arguments by copy or by reference.

 

That was too fast. So the details will follow.

Creation and execution of a thread

Now, a more formal approach: a thread gets a Callable and starts it immediately.

This sentence needs a few notes.

  • A Callable is an entity that behaves like a function. It can be a function, a function object, or a lambda function.
  • A function object is an instance of a class for which the call operator is overloaded. The key difference between functions and function objects is that a function object can have a state.
  • A lambda (anonymous function) is a pure function body without a name. It can be invoked just in place. A lambda function can capture its calling context. That’s why they are often called closures.

After the theory, a small example.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// createThread.cpp

#include <iostream>
#include <thread>

void helloFunction(){
  std::cout << "Hello C++11 from function." << std::endl;
}

class HelloFunctionObject  {
  public:
    void operator()() const {
      std::cout << "Hello C++11 from a function object." << std::endl;
    }
};


int main(){

  std::cout << std::endl;

  // thread executing helloFunction
  std::thread t1(helloFunction);

  // thread executing helloFunctionObject
  HelloFunctionObject helloFunctionObject;
  std::thread t2(helloFunctionObject);

  // thread executing lambda function
  std::thread t3([]{std::cout << "Hello C++11 from lambda function." << std::endl;});

  // ensure that t1, t2 and t3 have finished before main terminates
  t1.join();
  t2.join();
  t3.join();

  std::cout << std::endl;

};

 

 

Rainer D 6 P2 500x500Modernes C++ Mentoring

  • "Fundamentals for C++ Professionals" (open)
  • "Design Patterns and Architectural Patterns with C++" (open)
  • "C++20: Get the Details" (open)
  • "Concurrency with Modern C++" (open)
  • "Generic Programming (Templates) with C++": October 2024
  • "Embedded Programming with Modern C++": October 2024
  • "Clean Code: Best Practices for Modern C++": March 2025
  • Do you want to stay informed: Subscribe.

     

    All threads –  t1, t2, and t3 – write their messages to the console. The work package of thread t2 is a function object (lines 10 – 15), and the work package of thread t3 is a lambda function (line 29). In lines 32 – 34, the Main thread or Parent waits until his children are done.

    Let’s have a look at the output. This is more interesting.

     createThread

    The two programs’ execution results differ in two aspects. First, child threads will be executed in a different order. Second, the output is a little bit of a mess. So, in the second run, the line break of the function helloFunction happens after the lambda function call.

    What’s next?

    The next article will be about the lifetime of a thread. (Proofreader Alexey Elymanov)

     

     

     

     

    Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Stephen Kelley, Kyle Dean, Tusar Palauri, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, Marco Parri Empoli, Philipp Lenk, Charles-Jianye Chen, Keith Jeffery, Matt Godbolt, and Honey Sukesan.

    Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.

    My special thanks to Embarcadero
    My special thanks to PVS-Studio
    My special thanks to Tipi.build 
    My special thanks to Take Up Code
    My special thanks to SHAVEDYAKS

    Modernes C++ GmbH

    Modernes C++ Mentoring (English)

    Do you want to stay informed about my mentoring programs? Subscribe Here

    Rainer Grimm
    Yalovastraße 20
    72108 Rottenburg

    Mobil: +49 176 5506 5086
    Mail: schulung@ModernesCpp.de
    Mentoring: www.ModernesCpp.org

    Modernes C++ Mentoring,

     

     

    0 replies

    Leave a Reply

    Want to join the discussion?
    Feel free to contribute!

    Leave a Reply

    Your email address will not be published. Required fields are marked *