C++11 Multithreading--Basic use

Source: Internet
Author: User

c++11 Multithreading – Basic use

This article is only for the use of C++11 line libraries children's shoes to get started quickly, but also a simple record of their own, content comparison basis.

-1. Basic use of threads
-2. Mutex Amount
-3. Condition variables
-4. Atomic variables

1. Basic use of Threads Code:
#include <stdio.h>#include <stdlib.h>#include <assert.h>#include <thread>#include <iostream>intK =0;voidFunvoid){//thread hibernation, Chrono is the c++11 time-related library.           STD:: This_thread::sleep_for (STD:: Chrono::seconds (3)); for(inti =0; I <Ten; ++i) {STD::cout<<"Hello World"<<STD:: Endl;    k++; }}intMainintargcChar*argv[]) {//Create thread object    STD:: Thread T1 (fun);//Output thread ID and CPU core count    STD::cout<<"ID:"<< t1.get_id () <<STD:: Endl;STD::cout<<"CPU:"<<STD:: Thread::hardware_concurrency () <<STD:: Endl;//main function Blocking wait thread endT1.join ();//main function and thread function detach execution, thread becomes background thread    //t1.detach ();    STD::cout<< k <<STD:: Endl;returnexit_success;}

Attention:
1.linux with GCC or clang must be-pthread connected to the line libraries, otherwise there will be an error.
2. The main thread function cannot prematurely end the newly created thread function, because in c++11, the thread is also an object, and the main function ends the thread object, which is destroyed.
3.t.join () is the main function blocking the wait thread end to end, the main function will continue to execute and block at return
T.detach () The main function and the thread function are separated, each executes its own, and the thread becomes a background thread.
4. Threads can be created by bind and lambda
A thread can be saved in a container to guarantee the declaration period of the thread object.
Note, however, that the thread does not have a copy constructor and has a move constructor.

You can see that the copy constructor is delete.

2. Mutex Amount

Divided into 4 kinds
Std::mutex exclusive mutex, cannot be used recursively
Std::timed_mutex exclusive mutex with timeout, cannot be used recursively
Std::recursive_mutex recursive mutex with no timeout function
Std::recursive_timed_mutex recursive mutex with timeout

Code:
#include <stdio.h>#include <stdlib.h>#include <assert.h>#include <iostream>#include <thread>#include <mutex>STD:: Mutex G_lock;inti =0;voidFuncvoid){//Use the RAII technique to release automatically when you leave the scope    STD::lock_guard<STD:: Mutex>locker (G_lock);//Normal mutex lock    //g_lock.lock ();i++;STD::cout<< I <<STD:: Endl;//Mutex lock unlock    //g_lock.unlock ();}intMainintargcChar*argv[]) {STD:: Thread T1 (func);STD:: Thread T2 (func);STD:: Thread t3 (func);    T1.join ();    T2.join (); T3.join ();returnexit_success;}

Attention:
1. Multiple acquisition of mutex may occur deadlock, so we call Std::recursive_mutex recursive lock, allow the same thread to obtain the lock more than once, generally do not use recursive lock, Reason: <1. Using recursive locks can complicate the logic of a program, Programs that use recursive locks can generally be simplified. <2. Recursive locking is less efficient than non-recursive locking. <3. Recursive locks can be re-entered in a limited number of times, and errors will be exceeded.
2. You can use a mutex with a timeout period to avoid blocking while waiting for the mutex to lock.
3.unique_lock: is a generic mutex wrapper class. Unlike Lock_guard, it also supports deferred locking, time locks, recursive locks, lock ownership transfers, and also supports the use of conditional variables. This is also a non-replicable class, but it is a class that can be moved.

3. Condition Variables

Blocks one or more threads until a notification or timeout is received from another thread to wake the currently blocked process
Conditional variables need to be used in conjunction with mutexes
The C++11 provides two conditional variables
1.std::condition_variable, with Std::unique_lock for wait operations
2.std::condition_variable_any, with the use of any mutex with lock,unlock, more flexible but slightly less efficient.
Wait for a condition variable also has an overloaded method, which allows you to set a condition that will first check whether the criterion satisfies the condition.

Principle:
When a wait function of an Std::condition_variable object is called, it uses Std::unique_lock (via Std::mutex) to lock the current thread. The current thread is blocked until another thread invokes the notification function on the same Std::condition_variable object to wake the current thread.

code: Implementing synchronization Queues with c++11 multithreading
#include <stdio.h>#include <stdlib.h>#include <assert.h>#include <mutex>#include <thread>#include <condition_variable>#include <iostream>#include <list>#include <vector>#include <memory>#include <unistd.h>Template<TypeNameT>classsynqueue{ Public://ConstructorsSynqueue (intMaxSize): M_maxsize (MaxSize) {}//Put T-type objects into the queue        voidPut (ConstT&AMP;X) {STD::lock_guard<STD:: Mutex>locker (M_mutex); while(Isfull ()) {//If it's full, waitM_notfull.wait (M_mutex); } m_queue.push_back (x);//Wake up a thread through a conditional variable, or all threads canM_notempty.notify_one (); }//Remove the T type Object from the queue        voidTake (t&x) {STD::lock_guard<STD::mutex> Locker (M_mutex); while(IsEmpty ()) {STD::cout<<"No resource ... please wait"<<STD:: Endl;            M_notempty.wait (M_mutex);            } x = M_queue.front ();            M_queue.pop_front ();        M_notfull.notify_one (); }//Determine if the queue is empty        BOOLEmpty () {STD::lock_guard<STD::mutex> Locker (M_mutex);returnM_queue.empty (); }//Determine if the queue is full        BOOLFull () {STD::lock_guard<STD::mutex> Locker (M_mutex);returnM_queue.size () = = M_maxsize; }//return queue sizesize_t Size () {STD::lock_guard<STD::mutex> Locker (M_mutex);returnM_queue.size (); }Private://Judge empty or full, internal use does not need to lock        BOOLIsfull ()Const{returnM_queue.size () = = M_maxsize; }BOOLIsEmpty ()Const{returnM_queue.empty (); }Private://Queue        STD:: list<T>M_queue;//Mutual exclusion lock        STD:: Mutex M_mutex;//NOT NULL when the condition variable        STD:: Condition_variable_any m_notempty;//Not full-time condition variable        STD:: Condition_variable_any m_notfull;//Queue Maximum length        intM_maxsize;};voidFunc (synqueue<int> *sq) {intRet Sq->take (ret);STD::cout<< ret <<STD:: Endl;}intMainintargcChar*argv[]) {//Create thread queue with a maximum length ofsynqueue<int>syn ( -);//Drop Data Object     for(inti =0; I <Ten; i++) {syn.    Put (i); }STD::cout<< syn. Size () <<STD:: Endl;//threads cannot be copied, use containers and smart pointers to manage thread survival    STD:: Vector<std::shared_ptr<std::thread>> Tvec;//multi-cycle, insufficient resources, block the last thread, add a resource later to see if the thread will be awakened to execute.      for(inti =0; I < One; i++) {//Create threads and save smart pointers to management threads in containersTvec.push_back (STD::make_shared<STD::thread> (func, &syn));//Become a background threadTvec[i]->detach (); } Sleep (Ten);//Add a resourceSyn. Put ( One); SleepTen);returnexit_success;}

Operation Result:

4. Atomic Variables

Atomic variable, for atomic operation, no need to lock
std::atomic<T>
For more information, here is a simple example of how to use
Cppreference Atomic

Code:
#include <stdio.h>#include <stdlib.h>#include <assert.h>#include <atomic>#include <thread>#include <vector>#include <iostream>//Create an atomic variable of type intSTD::atomic<int&GT;ATC (0);voidFunc () {STD::cout<< ATC <<STD:: Endl; Atomic variable self-increment atc++;}intMainintargcChar*argv[]) {STD:: Vector<std::thread>Tvec; for(inti =0; I <Ten; i++) {STD:: Thread T (func);//Thread object move semanticsTvec.push_back (STD:: Move (t));    Tvec[i].join (); }returnexit_success;}

Finish

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

C++11 Multithreading--Basic use

Related Article

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.