Title: Sub-thread loop 10 times, then the main thread loop 100 times, then back to the child thread loop 10 times, and then back to the main thread and loop 100 times, so Loop 50 times, try to write code
The child thread and the main thread must have a condition (flag = = num), and the thread that does not satisfy the condition cannot get Unique_lock (it will be released in wait), only the thread that satisfies the condition can acquire the lock, execute the program
Mutex m;//mutually exclusive access to protection conditionsCondition_variable cond;//condition VariableintFlag =Ten;//conditionsvoidFunintnum) { for(inti =0; i< -; i++) {Unique_lock<mutex> LK (m);//A Unique Lock is an object, manages A mutex object with a unique ownership in both states:locked and unlocked. while(Flag! =num) cond.wait (LK);//Lk.unlock () is executed when wait is called for(intj =0; j<num; J + +) cout<< J <<" "; cout<<Endl; Flag= (num = =Ten) ? -:Ten; Cond.notify_one ();//The blocked thread wakes up after Lk.lock () resumes the state before calling wait }}intmain () {thread Child (fun,Ten); Fun ( -); Child.join (); System ("Pause"); return 0;}
Title: Write a program, open 3 threads, the IDs of the 3 threads are a, B, C, each thread prints its own ID on the screen 10 times, the output must be displayed in the order of ABC, such as: Abcabc .... recursion in turn.
Mutex m;condition_variable cond;intloop =Ten;intFlag =0;voidFuncintID) { for(inti =0; I < loop; ++i) {unique_lock<mutex>LK (m); while(Flag! =ID) cond.wait (LK); cout<< static_cast<Char> ('A'+ ID) <<" "; Flag= (flag +1) %3; Cond.notify_all (); }}voidmain () {thread A (func,0); Thread B (func,1); Func (2); cout<<Endl; A.join (); B.join (); System ("Pause");}
Topic (Google written question): There are four threads 1, 2, 3, 4. The function of thread 1 is output 1, the function of thread 2 is output 2, etc... There are now four file ABCD. The initial is empty. Now you want four files to appear in the following format:
A:1 2 3 4 1 2 ....
B:2 3 4 1 2 3 ....
C:3 4 1 2 3 4 ....
D:4 1 2 3 4 1 ....
Mutex m;condition_variable cond;intloop =Ten;intFlag;voidFuncintnum) { for(inti =0; I < loop; ++i) {unique_lock<mutex>LK (m); while(num! =flag) cond.wait (LK); cout<< num +1<<" "; Flag= (flag +1) %4; Cond.notify_all (); }}voidMainintargcChar*argv[]) {Flag= Atoi (argv[1]); Thread One (func,1); Thread (func),2); Thread Three (func,3); Func (0); One.join (); Two.join (); Three.join (); cout<<Endl; System ("Pause");}
Reader Writer's question
This is also a very classic multi-threaded topic, the main idea is as follows: There is a writer a lot of readers, many readers can read the file at the same time, but the writer does not allow readers to write the file, the reader is also read when the writer can not write.
This is implemented using copy on write (copy-on-write), mainly to understand the use of smart pointer std::shared_ptr, using the access vector to replace the file in the topic, the code is as follows:
Http://c.biancheng.net/cpp/html/2601.html
intReadernum =0; mutex M;mutex RW;voidwriter () {rw.Lock(); cout<<"I am writing"<<Endl; Rw.unlock ();}voidReader () {m.Lock(); if(Readernum = =0) rw.Lock(); Readernum++; M.unlock (); cout<<"I am reading"<<Endl; M.Lock(); Readernum--; if(Readernum = =0) Rw.unlock (); M.unlock ();}voidmain () {thread wr1 (writer); Thread Rd1 (reader); Wr1.join (); Rd1.join (); System ("Pause");}
Thread-Safe queue
The queue in the STL is non-thread-safe, a combination of operations: front (); Pop () first reads the first element of the team and then deletes the first element, and if multiple threads perform this combination, the execution sequence may occur alternately, leading to some unexpected behavior. Therefore, the interface of the thread-safe queue needs to be redesigned.
Template<typename t>classthreadsafe_queue{Private: mutable Std::mutex mut; Std::queue<T>Data_queue; Std::condition_variable Data_cond; Public: Threadsafe_queue () {} threadsafe_queue (Threadsafe_queueConst&Other ) {Std::lock_guard<std::mutex>LK (Other.mut); Data_queue=Other.data_queue; } voidPush (T New_value)//Queued Operation{Std::lock_guard<std::mutex>LK (mut); Data_queue.push (New_value); Data_cond.notify_one (); } voidWait_and_pop (t& value)//until an element can be deleted{Std::unique_lock<std::mutex>LK (mut); Data_cond.wait (LK, [ This] {return!data_queue.empty ();}); Value=Data_queue.front (); Data_queue.pop (); } std::shared_ptr<T>Wait_and_pop () {Std::unique_lock<std::mutex>LK (mut); Data_cond.wait (LK, [ This] {return!data_queue.empty ();}); Std::shared_ptr<T> Res (std::make_shared<t>(Data_queue.front ())); Data_queue.pop (); returnRes; } BOOLTry_pop (t& value)//whether or not the first element of the team returns directly{Std::lock_guard<std::mutex>LK (mut); if(Data_queue.empty ())return false; Value=Data_queue.front (); Data_queue.pop (); return true; } std::shared_ptr<T>Try_pop () {Std::lock_guard<std::mutex>LK (mut); if(Data_queue.empty ())returnStd::shared_ptr<t>(); Std::shared_ptr<T> Res (std::make_shared<t>(Data_queue.front ())); Data_queue.pop (); returnRes; } BOOLEmpty ()Const{Std::lock_guard<std::mutex>LK (mut); returnData_queue.empty (); }};
C + + multithreaded programming: Frequent meeting questions