Visual Studio 11 Development Guide (16) C ++ 11 Update-multithreading and Asynchronous Operation Management

Source: Internet
Author: User
Tags old windows

Standard C ++ 11 enhanced by Visual Studio 11

The new header files in STL that support this preview of the Visual Studio header can be programmed in multiple threads and managed asynchronously.

<Thread>, <future>, <atomic>, <time>, <mutex>, <condition_variable>, <ratio>, <filesystem>

Header file <thread> as its name to create and operate threads

 

1.thread t([]() 2.    {     3.     cout <<  "ThreadID : " << std::this_thread::get_id() << endl;         4.    });         5.    t.join();

This is a method of the constructor passed to the class of the thread, rather than introducing the C ++ 11 join () method in Lambda expression. This is a call blocking, wait for the main thread until the thread completes its work. If you want to decouple the type thread of the variable, the thread calls the detach () method in windows. In this way, the detach () method violates the plan, it does not affect the window (closehandle) associated with the thread handle ). Therefore, it may be that the T-line variable is used. The old Windows API retrieves the local handle, but the code will become much less portable.

 

1.WaitForSingleObject(t.native_handle()._Hnd ,INFINITE); 2.    t.detach();

 

In the thread, the join () method is essentially the same. The above Code (on the Windows platform ).

It is also likely to match the number of virtual processors available to use the hardware_concurrency () method,

unsigned numLogicalProc=t.hardware_concurrency(); 

 

The operating thread is always critical to synchronization and protection. Header <mutex> provides examples of mutually exclusive synchronization objects.
Note that using locks always affects performance!

 std::this_thread::sleep_for (chrono::seconds(1)); 5.    for(int i=0;i<10;i++) 6.    {     7.        m.lock(); 8.            cout <<  "ThreadID : " << std::this_thread::get_id() << ":" << i << endl;         9.        m.unlock (); 10.    } 11.});         12.thread t2([&m]() 13.{          14.    std::this_thread::sleep_for (chrono::seconds(1)); 15.    for(int i=0;i<10;i++) 16.    {         17.        m.lock (); 18.            cout <<  "ThreadID : " << std::this_thread::get_id() << ":" << i << endl;         19.        m.unlock(); 20.    } 21.}); 22.t1.join();     23.t2.join();    

 

 

Note that the this_thread namespace is used to retrieve the ID number or time class of the current thread.

It is also executed to control the use of the header file <condition_variable> for the example below by the producer/consumer as multiple thread streams.
Note that we make the consumer and producer mutually exclusive. We turn to the type of the variable condition_variable_any (which may also use the condition_variable unique_lock <mutex> type, the latter mutex is passed directly to the unreported status during initialization of the unique_lock type. Non-termination status indicates that the mutex can be obtained .)

 

1.mutex lockBuffer; 2.volatile BOOL ArretDemande=FALSE; 3.queue<long> buffer;         4.condition_variable_any cndNotifierConsommateurs; 5.condition_variable_any cndNotifierProducteur;     6.  7.thread ThreadConsommateur([&]() 8.{ 9.     10.    while(true) 11.        { 12.             13.            lockBuffer.lock (); 14.            while(buffer.empty () && ArretDemande==FALSE) 15.            {                     16.                cndNotifierConsommateurs.wait(lockBuffer); 17.            } 18.            if (ArretDemande==TRUE && buffer.empty ()) 19.            { 20.                lockBuffer.unlock(); 21.                cndNotifierProducteur.notify_one (); 22.                break; 23.            } 24.             25.            long element=buffer.front(); 26.            buffer.pop (); 27.            cout << "Consommation element :" << element << " Taille de la file :" << buffer.size() << endl; 28.             29.            lockBuffer.unlock (); 30.            cndNotifierProducteur.notify_one (); 31.        } 32.         33.}); 34. 35.thread ThreadProducteur([&]() 36.{ 37.    //Operation atomic sur un long 38.    std::atomic<long> interlock; 39.    interlock=1;     40.    while(true) 41.    { 42.            ////Simule une charge 43.            std::this_thread::sleep_for (chrono::milliseconds (15));                 44.            long element=interlock.fetch_add (1); 45.            lockBuffer.lock (); 46.            while(buffer.size()==10 && ArretDemande ==FALSE) 47.            { 48.                 49.                cndNotifierProducteur.wait (lockBuffer); 50.            } 51.            if (ArretDemande==TRUE) 52.            { 53.                 54.                lockBuffer.unlock (); 55.                cndNotifierConsommateurs.notify_one (); 56.                break; 57.            } 58.            buffer.push(element); 59.            cout << "Production unlement :" << element << " Taille de la file :" << buffer.size() << endl; 60.            lockBuffer.unlock (); 61.            cndNotifierConsommateurs.notify_one (); 62.    } 63. 64.}); 65.     66.  67.std::cout << "Pour arreter pressez [ENTREZ]" << std::endl; 68.getchar(); 69.     70.std::cout << "Arret demande" << endl; 71.ArretDemande=TRUE; 72. 73.ThreadProducteur.join(); 74.ThreadConsommateur.join();

 

In the example, the mutex is passed to the method without signal using the lock. However, if the queue is empty, it can be executed in the execution sequence.

This mutex is used to protect the <int> buffer type at the end. The wait () method uses another mechanism to suspend this and will wait to wake up. The producer thread is only used when it will call its method yy_one ().

Use the element type here to increment by 1 the elements of our queue in a single atomic operation. In the multi-threaded context, in addition, for example, it will always be fair to ensure that element operations are not preemptible.

 

Header file <future>. In the future, there will be no non-synchronous or thread traffic control mechanism after retrieval of the returned results for executing asynchronous operations. In the example, the join () method and the control flow object of multiple threads acting as mutex.

In fact, assume that you want to simply add two integers A + B, but the result is returned by two different threads.

In the following example, it is used as a concept to determine when to execute

 

1.std::cout << "Thread Principale : ID : " << std::this_thread::get_id() << endl;         2.    future<int> f1(async([]()->int 3.    { 4.        //Simule une charge 5.        std::this_thread::sleep_for (chrono::milliseconds (2000));                         6.        std::cout << "Future 1  ID : " << std::this_thread::get_id() << endl; 7.         8.        return 42; 9.    })); 10.  11.    future<int> f2(async([]()->int 12.    { 13.         14.        std::cout << "Future 2 ID : " << std::this_thread::get_id() << endl; 15.         16.        return 84; 17.    })); 18.     19.    std::cout << "Resultat : " << f1.get () + f2.get() << endl ; 20.    

Here we declare that the two values of the int type use the asynchronous type as the constructor of the parameter, which serves as the indication for executing asynchronous operations in different threads.

The two results will be returned in the future, but they do not know when to execute the get () method. This is a correct example of adding two integers in a call.
In future vs11 calls, we will use Asynchronous execution with a syntax close to the synchronous syntax.

 

Download vs11 now

Http://www.microsoft.com/click/services/Redirect2.ashx? Cr_cc = 200098144

 

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.