c++--multithreaded Programming (i) std::thread__linux

Source: Internet
Author: User
(i) header files related to c++11 multithreading

The c++11 new standard introduces four header files to support multithreaded programming, respectively, < atomic>,< thread>,< mutex>,< condition_variable> and < Future>.
< atomic>: The header mainly declares two classes, std::atomic and Std::atomic_flag, and also declares a set of C-style atomic types and functions with C-compatible atomic operations.
< thread>: The header file mainly declares the Std::thread class, and the Std::this_thread namespace is also in the header file.
< mutex>: This header file primarily declares classes related to mutexes (mutexes), including Std::mutex series classes, Std::lock_guard, Std::unique_lock, and other types and functions.
< condition_variable>: The header file mainly declares the classes associated with the condition variable, including std::condition_variable and Std::condition_variable_any.
< future>: The header document mainly declares std::p romise, std::p ackage_task Two Provider classes, as well as std::future and std::shared_future two future classes, and the other There are some types and functions associated with them, and the Std::async () function is declared in this header file. (ii) Std::thread 0 0.1 thread State

During the lifetime of a thread, you can convert between States, different operating systems can implement different threading models, define many different thread states, and each state can contain multiple child states, but generally, the following States are common:

1 Ready: Participate in the scheduling, waiting to be executed, once the schedule is selected, immediately start execution

2) Run: CPU occupied, running

3) Hibernate: Temporarily do not participate in scheduling, waiting for specific events to occur

4 Abort: Finished running, waiting for recycle thread resource 0.2 thread environment

Threads exist in the process, and all global resources within the process are visible to each thread inside.

Typical global resources in a process are as follows:

1 Code area: This means that all the visible function codes in the current process space are also visible for each thread.

2 Static Storage area: global variable, static space

3 Dynamic Storage area: Heap Space

Typical local resources within a thread:

1 Local stack space: Store the function call stack of this thread, the local variables inside the function, etc.

2 Partial Register variable: Thread next to execute pointer offsets for code 1 constructs, assigns, and copies 1.1 constructors

(1) Default:thread () noexcept;
(2) Initialization:template < class Fn, class ... args> Explicit Thread (fn&& Fn, Args&&. Args);
(3) Copy [deleted]: thread (const thread&) = delete;
(4) Move:thread (thread&& x) noexcept; The default constructor, which creates an empty thread execution object. Initializes the constructor, creates a thread object that can be joinable, and the newly generated thread invokes the FN function, which is given the parameter of the function by args. The copy constructor (disabled) means that thread cannot be copied. The move constructor, and X does not represent any thread execution objects after the call succeeds.

Note: Thread objects that can be joinable must be join by the main thread or set to detached before they are destroyed.

Chestnuts:

#include <iostream> #include <utility> #include <thread> #include <chrono> #include < functional> #include <atomic> void F1 (int n) {for (int i = 0; i < 5; ++i) {std::cout <& Lt
        "Thread" << n << "executing\n";
    Std::this_thread::sleep_for (Std::chrono::milliseconds (10));
        } void F2 (int& n) {for (int i = 0; i < 5; ++i) {std::cout << "Thread 2 executing\n";
        ++n;
    Std::this_thread::sleep_for (Std::chrono::milliseconds (10));
    int main () {int n = 0; Std::thread T1; T1 is not a thread std::thread T2 (f1, n + 1); Pass by value Std::thread t3 (F2, Std::ref (n)); Pass by reference std::thread T4 (Std::move (T3)); T4 is now running F2 ().
    T3 is no longer a thread t2.join ();
    T4.join (); Std::cout << "Final value of n is" << n << ' \ n ';}
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

Note: For Std::ref please refer to http://tieba.baidu.com/p/1292003201, https://zhidao.baidu.com/question/1240776856100751219.html

Possible output:

Thread 1 executing
thread 2 executing
thread 1 executing
thread 2 executing
thread 1 executing
Thread 2 executing
thread 1 executing
thread 2 executing
thread 2 executing
thread 1 executing
Final Value of N is 5
1 2 3 4 5 6 7 8 9 10 11 1.2 Move assignment Operation

Move (1):thread& operator= (thread&& rhs) noexcept; 
Copy [deleted] (2):thread& operator= ( Const thread&) = delete; Move assignment operation, if the current object is not joinable, you need to pass a right value reference (RHS) to the move assignment operation; If the current object can be joinable, terminate () the error. &NBSP
Note: Refer to the article http://www.ibm.com/developerworks/cn/aix/library/1307_lisl_c11/copy assignment operation is disabled and the thread object cannot be copied for the right value reference.

#include <stdio.h>//#include <stdlib.h> #include <chrono>//std::chrono::seconds #include <io 
    stream>//Std::cout #include <thread>//Std::thread, std::this_thread::sleep_for void thread_task (int n) {
    Std::this_thread::sleep_for (Std::chrono::seconds (n)); Std::cout << "Hello thread" << std::this_thread::get_id () << "Paused" << N <
< "seconds" << Std::endl; }/* = = = = FUNCTION ========================================================= * Name:main * DESCRIPTION:PR
Ogram entry routine.
    * ======================================================================== */int main (int argc, const char *argv[]) {
    Std::thread Threads[5];
    Std::cout << "spawning 5 threads...\n"; for (int i = 0; i < 5; i++) {Threads[i] = Std::thread (thread_task, i + 1);/******copy********/} std: : cout << "done spawning threads!
Now wait for them to join\n ";    for (auto& t:threads) {t.join ();

    } std::cout << "All Threads joined.\n";
    System ("pause");
return exit_success; }/*----------end of function main----------/*
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

Note: The FOR Loop statement in C++11 http://blog.csdn.net/hackmind/article/details/24271949 2 other member functions 2.1 get_id: Gets the thread ID.

Parameters: None
Return value: An object of member type THREAD::ID that uniquely identifies the thread (if joinable), or default-constructed (if not joinable)

Returns the thread ID.

If the Thread object is joinable, the function returns a value of that uniquely identifies the thread.

If the thread object is not joinable, the function returns a Default-constructed object of type Thread::id.

Chestnuts:

thread::get_id/this_thread::get_id
#include <iostream>       //std::cout
#include <thread>         //Std::thread, Std::thread::id, std::this_thread::get_id
#include <chrono>         //Std::chrono:: Seconds

Std::thread::id main_thread_id = std::this_thread::get_id ();

void Is_main_thread () {
  if (main_thread_id = = std::this_thread::get_id ())
    std::cout << "This is the main t Hread.\n ";
  else
    std::cout << "This are not the main thread.\n";
}

int main () 
{
  is_main_thread ();
  Std::thread th (is_main_thread);
  Th.join ();
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20-21

Output

This is the main thread.
This isn't the main thread.
1 2 2.2 joinable: Checks whether the thread can be join.

Return value: false, True
Parameters: None

Returns whether the thread object is joinable.

A thread object is joinable if it represents a thread of execution.

A Thread object is not joinable in any of these cases:
if it was default-constructed.
If it has been moved from (either constructing the thread object, or another to it).
if either of its members join or detach has been called.

Chestnuts:

//example for thread::joinable #include <iostream>//std::cout #include <thread> 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.