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)