Oh Look It s This Thread Again Templete

C++11/C++14 Thread one. Creating Threads

cplusplus_icon.png

Bookmark and Share




bogotobogo.com site search:


C++11/C++14 Thread Tutorials

C++11 i. Creating Threads

C++11 2. Debugging with Visual Studio 2013

C++11 3. Threading with Lambda Role

C++11 4. Rvalue and Lvalue

C++11 five. Move semantics and Rvalue Reference

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

C++11 half-dozen. Thread with Movement Semantics and Rvalue Reference

C++xi 7. Threads - Sharing Retentiveness and Mutex

C++11 eight. Threads - Race Weather condition

C++11 nine. Threads - Deadlock

C++11 10. Threads - Condition Variables

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

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

C++xi/C++fourteen New Features

initializer_list

Uniform initialization

Blazon Inference (auto) and Range-based for loop

The nullptr and strongly typed enumerations

Static assertions and Constructor delegation

override and concluding

default and delete specifier

constexpr and cord 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 initially approached C++11 thinking, "Yes, yes, I go it. It's C++, only more so." But as you learned more, you lot were surprised by the telescopic of the changes. automobile declarations, range-based for loops, lambda expressions, and rvalue references change the face up of C++, to say nothing of the new concurrency features. And and then there are the idiomatic changes. 0 and typedefs are out, nullptr and alias declarations are in. Enums should now exist scoped. Smart pointers are now preferable to built-in ones. Moving objects is ordinarily amend than copying them.
- Effective Modern C++ by Scott Meyers

C++xi Thread one. Creating Threads

Permit's await at the sample lawmaking (t1.cpp).

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

This lawmaking will impress out (on linux organisation):

$ 1000++ t1.cpp -o t1 -std=c++11 -pthread $ ./t2 thread function main thread        

First matter nosotros want to do is creating a thread object (worker thread) and requite it a work to do in a course of a function.

The chief thread wants to await for a thread to finish successfully. And then, nosotros used join(). If the initial main thread didn't expect for the new thread to end, it would continue to the end of main() and cease the program, possibly before the new thread have had a chance to run.

While the main thread is waiting, the master thread is idling. Actually, the Os may take the CPU abroad from the principal thread.

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

Beneath is the diagram how the flow looks like.

fork_join.png

Notwithstanding, in the real globe, things are not that platonic and more likely to exist asymmetric. Probably, it may await more than like the next picture.

real_fork_join.png

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

Detaching Threads

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

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

The detached child thread is at present free, and runs on its own. Information technology becomes a daemon process.

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

Notation that the detached thread didn't have a change to impress its output to stdout because the main thread already finished and exited. This is ane of the characteristics of multithreaded programming: we cannot be certain which thread runs offset (non deterministic unless we employ synchronization mechanism). In our case, because the fourth dimension information technology takes to create a new thread, the principal thread is most likely to finish ahead of our child thread.

Ane more than thing nosotros should note hither is that even in this simple lawmaking we're sharing a common resource: std::cout. So, to make the code piece of work properly, the primary thread should permit our child thread to access the resources.

Once a thread detached, we cannot force information technology to join with the main thread again. And so, the following line of the code is an mistake and the program volition crash.

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

Once detached, the thread should alive that way forever.

Nosotros can keep the code from crashing by checking using joinable(). Because information technology'south not joinable, the bring together() office won't be chosen, and the program runs without crash.

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

Callable Objects

In the previous examples, we used regular role for the thread task. However, we can use whatever callable object such every bit lambda functions as described in the next section or functor (function objects - come across Functors (Function Objects) I - Introduction) every bit 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 << "chief thread\northward";     t.join();     render 0; }        

Here, we created an office object and assign information technology to a thread task.

Nosotros may be temped to pass the example on the wing:

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

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

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

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

Why? I practice not want to go deep, just information technology'due south related to the office declaration convention in C++.

Passing Parameters to a thread

Hither is an instance of passing parameter to a thread. In this case, we're just passing a cord:

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

From the post-obit output, we know the string has been passed to the thread office successfully.

thread function bulletin is = Kathy Perry chief thread message = Kathy Perry        

If we want to laissez passer the string every bit a ref, we may want to try this:

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

To make information technology sure that the string is actually passed by reference, we modified the message at the terminate of the thread function. Notwithstanding, the output hasn't been changed.

thread role message is = Kathy Perry chief thread bulletin = Kathy Perry        

In fact, the message was passed past value non by reference. To pass the message by reference, we should modify the code a little flake similar this using ref:

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

Then, we become modified output:

thread function message is = Kathy Perry chief thread bulletin = Justin Beaver        

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

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

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

thread role message is = Kathy Perry main thread message =        

Thread copy / move

Copying a thread won't compile:

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

Just 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 << "master thread\n";     std::thread          t2 = move(t);      t2.bring together();      render 0; }        

Output:

$ k++ t5.cpp -o t5 -std=c++11 -pthread $ ./t5 main thread thread function        

Thread id

Nosotros can get id data using this_thread::get_id():

int master() {     std::cord s = "Kathy Perry";     std::thread t(&thread_function, std::move(s));     std::cout << "main thread bulletin = " << due south << 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();     render 0; }        

Output:

thread role message is = Kathy Perry main thread message = main thread id = 1208 child thread id = 5224        

How many threads?

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

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

Output:

Number of threads = two        

lambda functions

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

We tin replace the thread_function() with lambda function (bearding office) like this:

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

Note that we are writing inline code and passing into some other role 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 instance, taking no argument. So, in essence, we're using [](){} equally a task, and assigning it to our thread.

C++11/C++fourteen Thread Tutorials

C++xi 1. Creating Threads

C++eleven 2. Debugging with Visual Studio 2013

C++11 iii. Threading with Lambda Function

C++11 4. Rvalue and Lvalue

C++11 5. Move semantics and Rvalue Reference

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

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

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

C++11 8. Threads - Race Conditions

C++eleven 9. Threads - Deadlock

C++11 ten. Threads - Status Variables

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

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

C++11/C++14 New Features

initializer_list

Uniform initialization

Type Inference (automobile) 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::assortment container

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

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

mcclainthioseen37.blogspot.com

Source: https://www.bogotobogo.com/cplusplus/C11/1_C11_creating_thread.php

0 Response to "Oh Look It s This Thread Again Templete"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel