Thread Creation

Contents[Show]

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.

 

Rainer D 6 P2 540x540Modernes C++ Mentoring

Be part of my mentoring programs:

 

 

 

 

Do you want to stay informed about my mentoring programs: Subscribe via E-Mail.

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;

};

 

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, Animus24, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, 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, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, and Rob North.

 

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

 

 

My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small

 

My special thanks to PVS-Studio PVC Logo

 

My special thanks to Tipi.build tipi.build logo

 

My special thanks to Take Up Code TakeUpCode 450 60

 

Seminars

I'm happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

Bookable (Online)

German

Standard Seminars (English/German)

Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

  • C++ - The Core Language
  • C++ - The Standard Library
  • C++ - Compact
  • C++11 and C++14
  • Concurrency with Modern C++
  • Design Pattern and Architectural Pattern with C++
  • Embedded Programming with Modern C++
  • Generic Programming (Templates) with C++

New

  • Clean Code with Modern C++
  • C++20

Contact Me

Modernes C++,

RainerGrimmDunkelBlauSmall

Comments   

0 #1 muban777.com 2016-07-09 18:42
Some genuinely good blog posts on this web site, thank you for contribution.
Quote
0 #2 JasaPoker.net 2016-09-17 22:42
Peculiar article, totally what I needed.
Quote
0 #3 taruhan bola 2016-09-23 05:09
This piece of writing gives clear idea designed for the new users of blogging, that actually how
to do blogging and site-building.
Quote
0 #4 Get coupon now 2016-10-07 22:40
I go to see everyday a few web pages and websites to read posts, except this blog
provides feature based writing.
Quote
0 #5 Bandar Bola ternama 2016-11-23 08:06
continuously i used to read smaller posts which as well clear their motive, and that is also happening with this piece of writing which I am reading now.
Quote
0 #6 Bandar Bola Terbesar 2016-11-27 00:48
Wow, this paragraph is good, my younger sister is analyzing
these kinds of things, thus I am going to let know her.
Quote
0 #7 agen poker terbesar 2016-11-28 15:11
I've been surfing on-line more than 3 hours lately, but I by no means
found any interesting article like yours. It's beautiful price sufficient for me.
In my opinion, if all webmasters and bloggers made just
right content as you probably did, the web will likely be
a lot more helpful than ever before.
Quote
0 #8 Indo-bet8 2016-12-17 01:47
I needed to thank you for this excellent read!! I certainly enjoyed every bit
of it. I have got you saved as a favorite to look at new stuff you post…
Quote
0 #9 Amos 2016-12-17 05:32
I do trust all the ideas you've introduced to your post.
They are really convincing and can certainly work. Nonetheless, the posts are very short for beginners.
May you please prolong them a bit from subsequent time?
Thank you for the post.
Quote

Stay Informed about my Mentoring

 

Mentoring

English Books

Course: Modern C++ Concurrency in Practice

Course: C++ Standard Library including C++14 & C++17

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Course: The All-in-One Guide to C++20

Course: Master Software Design Patterns and Architecture in C++

Subscribe to the newsletter (+ pdf bundle)

All tags

Blog archive

Source Code

Visitors

Today 3984

Yesterday 4344

Week 40862

Month 21108

All 12099317

Currently are 173 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments