34. Conditional variables and multithreading (unicast vs. multicast)

Source: Internet
Author: User
Tags mutex

1 #define_crt_secure_no_warnings2#include <iostream>3#include <thread>4#include <mutex>5#include <condition_variable>6 using namespacestd;7 8 //thread communication, combined with mutexes9 //one thread, multiple threads waiting, notifying one or notifying multipleTen  OneMutex m;//threads Repel each other ACondition_variable CV;//threads communicate with each other -  - voidMain () the { -Thread **th =Newthread*[Ten];//array of pointers to open threads -      for(inti =0; I <Ten; i++) -     { +Th[i] =NewThread ([] (intindex) -         { +             /*The Std::lock_guard of a mutex is the ability to lock the mutex when the object is constructed, A The mutex is unlocked at the time of the destructor so that a stack object guarantees that the mutex can be unlocked in the case of an Lock_guard object, at Lock_guard owns the ownership of the mutex. */ -             //initialize LCK with mutex to enter the wait state -Unique_lock<mutex>lck (m); -             //waiting for incoming traffic -Cv.wait_for (Lck, Chrono::hours ( +)); -cout << index << Endl;//Print Number in }, i); -     } to  +      -      the     //unlock mutexes by notifying each other *     //for (int i = 0; i <; i++) $     //{Panax Notoginseng         /*when a Lock_guard object is created, it tries to get ownership of the mutex that is given to it.  - when control is not in the range created by the Lock_guard object, the Lock_guard is refactored, the thereby the mutex is released. */ +         //lock_guard<mutex> lckg (m);//Unlock Wizard A         //Cv.notify_one (); the     //} +     //notify all, unlock mutex - Cv.notify_all (); $  $      for(inti =0; I <Ten; i++) -     { -Th[i]->join (); the Delete Th[i]; -     }Wuyi delete[] th; the  -Cin.Get(); Wu}

34. Conditional variables and multithreading (unicast vs. multicast)

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.