C++11 multithreading-Related header files

Source: Internet
Author: User
Tags mutex thread class

The c++11 new standard introduces four header files to support multithreaded programming, respectively <atomic>,<thread>,<mutex>,<condition_variable> and < Future>.

    • <atomic>: This article mainly declares two classes, std::atomic and Std::atomic_flag, and also declares a set of C-style atomic types and functions that are compatible with C 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>: The 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 primarily declares classes related to condition variables, including std::condition_variable and Std::condition_variable_any.
    • <future>: This header file mainly declares std::p romise, std::p ackage_task Two Provider classes, and Std::future and Std::shared_future two future classes, plus There are also types and functions associated with it, and the Std::async () function is declared in this header file.
Std::thread "Hello World"

Here is one of the simplest examples of using the Std::thread class:

#include <stdio.h> #include <stdlib.h> #include <iostream>//std::cout#include <thread>   / /Std::threadvoid Thread_task () {    std::cout << "Hello thread" << Std::endl;} /* * = =  FUNCTION  ========================================================= *         Name:  main *  Description: Program  entry routine. * ======================================================================== */int Main (int argc, const char *argv[]) {    std::thread T (thread_task);    T.join ();    return exit_success;}  /*----------  end of function main  ----------*/

Makefile as follows:

ALL:THREADCC=G++CPPFLAGS=-WALL-STD=C++11-GGDBLDFLAGS=-PTHREADTHREAD:THREAD.O    $ (CC) $ (LDFLAGS)-O [email Protected] $^thread.o:thread.cc    $ (cc) $ (cppflags)-o [email protected]-C $^. Phony:    Cleanclean:    rm thread.o Thread

Note that in a Linux GCC4.6 environment, you need to add-pthread at compile time, otherwise the execution will appear:

$./threadterminate called after throwing a instance of ' Std::system_error ' What  ():  Operation not Permittedaborted (Core dumped)

The reason is that GCC does not load the Pthread library by default, and it is said that in subsequent releases it is not possible to add the-pthread option at compile time.

Std::thread is declared in the <thread> header file, so it is necessary to include <thread> header files when using Std::thread.

Std::thread Construction
Default (1)
Thread () noexcept;
Initialization (2)
Template <class Fn, class ... Args>explicit Thread (fn&& Fn, Args&& .... Args);
copy [deleted] (3)
Thread (const thread&) = delete;
Move (4)
Thread (thread&& x) noexcept;
    • (1). The default constructor creates an empty thread execution object.
    • (2). Initialize the constructor, create a thread object, the thread object can be joinable, and the newly generated thread will call the FN function, which is given the parameters of the function.
    • (3). The copy constructor (disabled) means that the thread cannot be copied.
    • (4). Move constructor, move constructor, X does not represent any thread execution object 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.

Std::thread examples of various constructors are as follows (reference):

#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 << "Thread "<< n <<" executing\n ";        Std::this_thread::sleep_for (Std::chrono::milliseconds (Ten));}    } 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 (Ten));}    } 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 re Ference    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 ';}
Move Assignment action
Move (1)
thread& operator= (thread&& rhs) noexcept;
copy [deleted] (2)
thread& operator= (const thread&) = delete;
    • (1). Move assignment operation, if the current object is not joinable, you need to pass an rvalue reference (RHS) to the move assignment operation, or terminate () if the current object can be joinable.
    • (2). The copy assignment operation is disabled and the thread object cannot be copied.

Take a look at the following example:

#include <stdio.h> #include <stdlib.h> #include <chrono>//Std::chrono::seconds#include <    iostream>//Std::cout#include <thread>//Std::thread, std::this_thread::sleep_forvoid thread_task (int n) {    Std::this_thread::sleep_for (Std::chrono::seconds (n)); Std::cout << "Hello thread" << std::this_thread::get_id () << "paused" << N &LT;&L T "Seconds" << Std::endl;} /* * = = FUNCTION ========================================================= * Name:main * description:progr AM entry routine. * ======================================================================== */int Main (int argc, const char *argv[]) {s    Td::thread Threads[5];    Std::cout << "spawning 5 threads...\n";    for (int i = 0; i < 5; i++) {Threads[i] = Std::thread (thread_task, i + 1); } std::cout << "done spawning threads!    Now wait for them to join\n "; for (auto& t:threads) {t.join ();    } std::cout << "All Threads joined.\n";  return exit_success;} /*----------End of function main----------*/
Other member functions
    • get_id
gets the thread ID.
    • Joinable
checks whether a thread can be join.
    • Join
The Join thread.
    • Detach
Detach Threads
    • Swap
Swap thread.
    • Native_handle
Returns native handle.
    • hardware_concurrency [Static]
detects hardware concurrency characteristics.

C++11 multithreading-Related header files

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.