C++ Tutorial: C++11/C++14 Thread 1. Creating Threads (2023)

C++11/C++14 Thread1. Creating Threads

C++ Tutorial: C++11/C++14 Thread 1. Creating Threads (1)

C++ Tutorial: C++11/C++14 Thread 1. Creating Threads (2)



bogotobogo.com site search:

C++11 1. Creating Threads

C++11 2. Debugging with Visual Studio 2013

C++11 3. Threading with Lambda Function

C++11 4. Rvalue and Lvalue

C++11 5. Move semantics and Rvalue Reference

C++11 5B. Move semantics - more samples for move constructor

C++11 6. Thread with Move Semantics and Rvalue Reference

C++11 7. Threads - Sharing Memory and Mutex

C++11 8. Threads - Race Conditions

C++11 9. Threads - Deadlock

C++11 10. Threads - Condition Variables

C++11 11. Threads - unique futures (std::future<>)and shared futures (std::shared_future<>).

C++11 12. Threads - std::promise

initializer_list

Uniform initialization

Type Inference (auto) and Range-based for loop

(Video) C++11 Threads Tutorial

The nullptr and strongly typed enumerations

Static assertions and Constructor delegation

override and final

default and delete specifier

constexpr and string literals

Lambda functions and expressions

std::array container

Rvalue and Lvalue (from C++11 Thread tutorial)

Move semantics and Rvalue Reference (from C++11 Thread tutorial)

"If you're an experienced C++ programmer and are anything like me, you initiallyapproached C++11 thinking, "Yes, yes, I get it. It's C++, only more so." But as youlearned more, you were surprised by the scope of the changes. auto declarations,range-based for loops, lambda expressions, and rvalue references change the face ofC++, to say nothing of the new concurrency features. And then there are theidiomatic changes. 0 and typedefs are out, nullptr and alias declarations are in.Enums should now be scoped. Smart pointers are now preferable to built-in ones.Moving objects is normally better than copying them.
- Effective Modern C++ by Scott Meyers

C++11 Thread 1. Creating Threads

Let's look at the sample code (t1.cpp).

#include <iostream>#include <thread>void thread_function(){ std::cout << "thread function\n";}int main(){ std::thread t(&thread_function); // t starts running std::cout << "main thread\n"; t.join(); // main thread waits for the thread t to finish return 0;}

This code will print out (on linux system):

$ g++ t1.cpp -o t1 -std=c++11 -pthread$ ./t2thread functionmain thread

First thing we want to do is creating a thread object (worker thread) and give it a work to do in a form of a function.

The main thread wants to wait for a thread to finish successfully. So, we used join(). If the initial main thread didn't wait for the new thread to finish, it would continue to the end of main() and end the program, possibly before the new thread have had a chance to run.

While the main thread is waiting, the main thread is idling. Actually, the OS may take the CPU away from the main thread.

Note that we have a new Standard C++ Library header #include <thread> in which the functions and classes for threads are declared.

Below is the diagram how the flow looks like.

C++ Tutorial: C++11/C++14 Thread 1. Creating Threads (3)

However, in the real world, things are not that ideal and more likely to be asymmetric. Probably, it may look more like the next picture.

C++ Tutorial: C++11/C++14 Thread 1. Creating Threads (4)

(Video) C++ Multithreading Part - 1 : Creating & Managing Threads using built in constructs C++11 Onwards

While the worker thread is starting via constructor std::thread t, there might be overhead of creating a thread (this overhead can be reduced by using thread pool). The dotted line indicates a possible blocked state.

Detaching Threads

We can make a new thread to run free to become a daemon process.

// t2.cppint main(){ std::thread t(&thread_function); std::cout << "main thread\n"; // t.join(); t.detach(); return 0;}

The detached child thread is now free, and runs on its own. It becomes a daemon process.

$ g++ t2.cpp -o t2 -std=c++11 -pthread$ ./t2main thread

Note that the detached thread didn't have a change to print its output to stdout because the main thread already finished and exited. This is one of the characteristics of multithreaded programming: we cannot be sure which thread runs first (not deterministic unless we use synchronization mechanism). In our case, because the time it takes to create a new thread, the main thread is most likely to finish ahead of our child thread.

One more thing we should note here is that even in this simple code we're sharing a common resource: std::cout. So, to make the code work properly, the main thread should allow our child thread to access the resource.

Once a thread detached, we cannot force it to join with the main thread again. So, the following line of the code is an error and the program will crash.

int main(){ std::thread t(&thread_function); std::cout << "main thread\n"; // t.join(); t.detach(); t.join(); // Error return 0;}

Once detached, the thread should live that way forever.

We can keep the code from crashing by checking using joinable(). Because it's not joinable, the join() function won't be called, and the program runs without crash.

int main(){ std::thread t(&thread_function); std::cout << "main thread\n"; // t.join(); if(t.joinable()) t.join(); return 0;}

Callable Objects

In the previous examples, we used regular function for the thread task. However, we can use any callable object such as lambda functions as described in the next section or functor (function objects - see Functors (Function Objects) I - Introduction) as shown below:

#include <iostream>#include <thread>class MyFunctor{public: void operator()() { std::cout << "functor\n"; }};int main(){ MyFunctor fnctor; std::thread t(fnctor); std::cout << "main thread\n"; t.join(); return 0;}

Here, we created an function object and assign it to a thread task.

We may be temped to pass the instance on the fly:

// MyFunctor fnctor;std::thread t(MyFunctor());

But it won't compile. So, if we still want to make it work, we should do this instead:

// MyFunctor fnctor;std::thread t((MyFunctor()));

Note that we had to add () to enclose the MyFunctor().

Why? I do not want to go deep, but it's related to the function declaration convention in C++.

Passing Parameters to a thread

Here is an example of passing parameter to a thread. In this case, we're just passing a string:

#include <iostream>#include <thread>#include <string>void thread_function(std::string s){ std::cout << "thread function "; std::cout << "message is = " << s << std::endl;}int main(){ std::string s = "Kathy Perry"; std::thread t(&thread_function, s); std::cout << "main thread message = " << s << std::endl; t.join(); return 0;}

From the following output, we know the string has been passed to the thread function successfully.

thread function message is = Kathy Perrymain thread message = Kathy Perry

If we want to pass the string as a ref, we may want to try this:

void thread_function(std::string &s){ std::cout << "thread function "; std::cout << "message is = " << s << std::endl; s = "Justin Beaver";}

To make it sure that the string is really passed by reference, we modified the message at the end of the thread function. However, the output hasn't been changed.

thread function message is = Kathy Perrymain thread message = Kathy Perry

In fact, the message was passed by value not by reference. To pass the message by reference, we should modify the code a little bit like this using ref:

(Video) Using C11 Threads

std::thread t(&thread_function, std::ref(s));

Then, we get modified output:

thread function message is = Kathy Perrymain thread message = Justin Beaver

There is another way of passing the parameter without copying and not sharing memory between the threads. We can use move():

std::thread t(&thread_function, std::move(s));

Since the string moved from main() to thread function, the output from main does not have it any more:

thread function message is = Kathy Perrymain thread message =

Thread copy / move

Copying a thread won't compile:

#include <iostream>#include <thread>void thread_function(){ std::cout << "thread function\n";}int main(){ std::thread t(&thread_function); std::cout << "main thread\n"; std::thread t2 = t; t2.join(); return 0;}

But we can transfer the ownership of the thread by moving it:

// t5.cpp#include <iostream>#include <thread>void thread_function(){ std::cout << "thread function\n";}int main(){ std::thread t(&thread_function); std::cout << "main thread\n"; std::thread t2 = move(t); t2.join(); return 0;}

Output:

$ g++ t5.cpp -o t5 -std=c++11 -pthread$ ./t5main threadthread function

Thread id

We can get id information using this_thread::get_id():

int main(){ std::string s = "Kathy Perry"; std::thread t(&thread_function, std::move(s)); std::cout << "main thread message = " << s << std::endl; std::cout << "main thread id = " << std::this_thread::get_id() << std::endl; std::cout << "child thread id = " << t.get_id() << std::endl; t.join(); return 0;}

Output:

thread function message is = Kathy Perrymain thread message =main thread id = 1208child thread id = 5224

How many threads?

The thread library provides the suggestion for the number of threads:

int main(){ std::cout << "Number of threads = " << std::thread::hardware_concurrency() << std::endl; return 0;}

Output:

Number of threads = 2

lambda functions

Since we're dealing with C11, let's take a little break for "lambda".

We can replace the thread_function() with lambda function (anonymous function) like this:

int main(){ std::thread t([]() { std::cout << "thread function\n"; } ); std::cout << "main thread\n"; t.join(); // main thread waits for t to finish return 0;}

Note that we are writing inline code and passing into another function which is a thread constructor.

The lambda expression is a series of statements enclosed in braces, prefixed with [], called lambda introducer or capture specification which tells the compiler we're creating a lambda function, in our case, taking no argument. So, in essence, we're using [](){} as a task, and assigning it to our thread.

C++11 1. Creating Threads

C++11 2. Debugging with Visual Studio 2013

C++11 3. Threading with Lambda Function

C++11 4. Rvalue and Lvalue

(Video) All Threading Concepts In C++ OR C++11 With Code Example

C++11 5. Move semantics and Rvalue Reference

C++11 5B. Move semantics - more samples for move constructor

C++11 6. Thread with Move Semantics and Rvalue Reference

C++11 7. Threads - Sharing Memory and Mutex

C++11 8. Threads - Race Conditions

C++11 9. Threads - Deadlock

C++11 10. Threads - Condition Variables

C++11 11. Threads - unique futures (std::future<>)and shared futures (std::shared_future<>).

C++11 12. Threads - std::promise

initializer_list

Uniform initialization

Type Inference (auto) and Range-based for loop

The nullptr and strongly typed enumerations

Static assertions and Constructor delegation

override and final

default and delete specifier

constexpr and string literals

Lambda functions and expressions

std::array container

Rvalue and Lvalue (from C++11 Thread tutorial)

Move semantics and Rvalue Reference (from C++11 Thread tutorial)

(Video) Different Types To Create Threads In C++11

FAQs

How do you create a thread class in C++? ›

To start a thread we simply need to create a new thread object and pass the executing code to be called (i.e, a callable object) into the constructor of the object. Once the object is created a new thread is launched which will execute the code specified in callable. After defining callable, pass it to the constructor.

Can you create a C++11 thread with a function pointer that takes a bunch of arguments? ›

Can you create a C++11 thread with a function pointer that takes a bunch of arguments? 11. Can you create a C++11 thread with a lambda closure that takes a bunch of arguments? Yes – just like the previous case, you can pass the arguments needed by the lambda closure to the thread constructor.

How do you spawn a new thread in C++? ›

Using std:: thread we simply need to create a new thread object and pass it a callable. A callable is an executable code that we want to execute when the thread is running. So whenever we want a new thread, we just create an object of std:: thread and pass a callable as an argument to its constructor.

How many threads can I run C++? ›

There is nothing in the C++ standard that limits number of threads. However, OS will certainly have a hard limit. Having too many threads decreases the throughput of your application, so it's recommended that you use a thread pool.

What are the 3 basic types of threads? ›

There are three standard thread series in the Unified screw thread system that are highly important for fasteners: UNC (coarse), UNF (fine), and 8-UN (8 thread).

What happens if you spawn too many threads? ›

You need to prevent too many threads from being spawned, a problem that could potentially result in a denial of service owing to exhausted system resources.

How will you create a thread give example? ›

You can create threads by implementing the runnable interface and overriding the run() method. Then, you can create a thread object and call the start() method. Thread Class: The Thread class provides constructors and methods for creating and operating on threads.

Is C++ single threaded by default? ›

Every C++ program has at least one thread, which is started by the C++ runtime: the thread running main() . Your program can then launch additional threads that have another function as the entry point.

Why do we use threads in C++? ›

Thread-based multitasking deals with the concurrent execution of pieces of the same program. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.

What are the steps of threading? ›

How do I thread the machine (Threading the upper thread).
  1. Turn on the sewing machine.
  2. Raise the presser foot lever. ...
  3. Press. ...
  4. Remove the spool cap that is inserted onto the spool pin.
  5. Place the spool of thread onto the spool pin. ...
  6. Slide the spool cap onto the spool pin.
Jun 2, 2014

Do C++ threads use multiple cores? ›

C++ Multithreading

Not only does this take advantage of multiple CPU cores, but it also allows the developer to control the number of tasks taken on by manipulating the thread pool size. The program can then use the computer resources efficiently without overloading becoming overloaded.

How do I know how many threads to use? ›

Just give me the formula!
  1. Number of threads = Number of Available Cores * (1 + Wait time / Service time)
  2. Number of threads = Number of Available Cores * Target CPU utilization * (1 + Wait time / Service time)
  3. 22 / 0.055 = 400 // the number of requests per second our service can handle with a stable response time.
Apr 18, 2019

What is the maximum number of threads? ›

The maximum threads setting specifies the maximum number of simultaneous transactions that the Web Server can handle. The default value is greater of 128 or the number of processors in the system. Changes to this value can be used to throttle the server, minimizing latencies for the transactions that are performed.

How many threads are allowed? ›

A single CPU core can have up-to 2 threads per core. For example, if a CPU is dual core (i.e., 2 cores) it will have 4 threads.

How do you spawn a new thread? ›

To spawn a Java thread, follow these steps:
  1. Create your class, making it implement the Runnable interface. ...
  2. Define a method within your class with this signature:
  3. Create an instance of your class. ...
  4. Create a new thread attached to your new instance. ...
  5. Start the thread attached to your object.

Can a thread spawn another thread C++? ›

A thread does not operate within another thread. They are independent streams of execution within the same process and their coexistence is flat, not hierarchical. Some simple rules to follow when working with multiple threads: Creating threads is expensive, so avoid creating and destroying them rapidly.

What is __ thread in C++? ›

The __thread storage class marks a static variable as having thread-local storage duration. This means that in a multi-threaded application a unique instance of the variable is created for each thread that uses it and destroyed when the thread terminates.

Does async create a new thread C++? ›

The C++ standard says: The function template async provides a mechanism to launch a function potentially in a new thread and provides the result of the function in a future object with which it shares a shared state.

Videos

1. Join And Detach With Joinable | Threading In C++11
(CppNuts)
2. Building Multi-threaded Applications with C++11 Lesson 1: Getting Started
(Jon Toews)
3. How to use threads in C++11 (multitasking, mutual exclusion, etc.)
(Bisqwit)
4. An Effective C++11/14 Sampler
(Paulo Portela)
5. Build your first multithreaded application - Introduction to multithreading in modern C++
(CodeBeauty)
6. C++ Threading #1: Introduction
(Bo Qian)

References

Top Articles
Latest Posts
Article information

Author: Lilliana Bartoletti

Last Updated: 10/19/2023

Views: 5702

Rating: 4.2 / 5 (53 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Lilliana Bartoletti

Birthday: 1999-11-18

Address: 58866 Tricia Spurs, North Melvinberg, HI 91346-3774

Phone: +50616620367928

Job: Real-Estate Liaison

Hobby: Graffiti, Astronomy, Handball, Magic, Origami, Fashion, Foreign language learning

Introduction: My name is Lilliana Bartoletti, I am a adventurous, pleasant, shiny, beautiful, handsome, zealous, tasty person who loves writing and wants to share my knowledge and understanding with you.