I asked about a manufacturer / consumer code which was more common (although the answers were definitely useful). That's why I have taken suggestions from another author and converted them into C ++ and encouraged them. However, I am always worried about the multi-thread code - so if anybody can see a clear correction that I want to hear about them.
#include & lt; Pthread.h & gt; #include & lt; Deque & gt; # Include & lt; Iostream & gt; #include "boost / thread.hpp" class MyQueue {protected: boost :: mutex mutex_; Promotion: condition_anless condition_; Cancel the bulge; Std :: Deque & LT; Integer & gt; Information_; Public: Mike (): mutex_ (), condition_ (), canceled_ (wrong), data_ () {} cancel} {}; Zero push (int i) (boost :: lock_guard & gt; boost :: mutex & gt; l (mutex_); if thrown (cancel);) data_.push_back (i); condition_.notify_all ();} Zero pop (IT and I) {boost :: unique_lock l (mutex_); while (cancel_and_date_size () == 0) {condition_.wait (l);} If (cancel) threw (); emphasize (data_.size ()! = 0); I = data_.front (); data_.pop_front ();} zero cancel () {boost :: lock_guard & lt ; Boost :: mutex & gt; l (mutex_); if thrown (canceled); Cancel_ = true; condition_.notify_all ();}}; Promotion: mute x iomutex; zero productive (mikuyu * q, Co Nost strode :: string & amp; name) {for (unsigned int i = 0; i push (i); to promote: lock_guard & lt; Promotion :: mutex> l (iomutex); std :: cout L (iomutex); Std :: cout & lt; & Lt; Name & lt; & Lt; "Productive conclusion" & lt; & Lt; Std :: endl; }} Catch (Mayuou :: Cancel and C) {boost :: lock_guard < Boost :: mutex & gt; L (iomutex); Std :: cout & lt; & Lt; Name & lt; & Lt; "Productive cancer" & lt; Std :: endl; } Zero subscribers (MyQueue * q, const std :: string and name) {while {true} {int i; Q- & gt; Pop (i); Promote: lock_guard & lt; Promotion :: Muttex & gt; L (iomutex); Std :: cout & lt; & Lt; Name & lt; & Lt; "Consumed" & lt; & Lt; I & lt; & Lt; Std :: endl; }} Catch (Mayuou :: Cancel and C) {boost :: lock_guard < Boost :: mutex & gt; L (iomutex); Std :: cout & lt; & Lt; Name & lt; & Lt; "Consumer Cancer" & lt; Std :: endl; } Int main () {MyQueue q; Promotion: thread pr1 (manufacturer, & q, "pro1"); Promotion: thread pr2 (manufacturer, & amp; q; "pro2"); Promotion: thread cons1 (consumer, & amp; q; "con1"); Promotion: thread cons2 (consumer, & quot; con2;); Pr1.join (); Pr2.join (); Cons1.join (); Cons2.join (); } Update: I ended up using a modified version. My revised edition can be found.
If you are worried about potential damage in your implementation, then you are the guardian of Anthony Williams ) Try to use Thread Library) Excellent thread-safe.
Comments
Post a Comment