यहाँ सी ++ 11 उपकरणों का उपयोग करने accepted answer to your first question का अनुवाद है:
#include <mutex>
#include <condition_variable>
#include <thread>
#include <stdio.h>
class AutoResetEvent
{
public:
explicit AutoResetEvent(bool initial = false);
void Set();
void Reset();
bool WaitOne();
private:
AutoResetEvent(const AutoResetEvent&);
AutoResetEvent& operator=(const AutoResetEvent&); // non-copyable
bool flag_;
std::mutex protect_;
std::condition_variable signal_;
};
AutoResetEvent::AutoResetEvent(bool initial)
: flag_(initial)
{
}
void AutoResetEvent::Set()
{
std::lock_guard<std::mutex> _(protect_);
flag_ = true;
signal_.notify_one();
}
void AutoResetEvent::Reset()
{
std::lock_guard<std::mutex> _(protect_);
flag_ = false;
}
bool AutoResetEvent::WaitOne()
{
std::unique_lock<std::mutex> lk(protect_);
while(!flag_) // prevent spurious wakeups from doing harm
signal_.wait(lk);
flag_ = false; // waiting resets the flag
return true;
}
AutoResetEvent event;
void otherthread()
{
event.WaitOne();
printf("Hello from other thread!\n");
}
int main()
{
std::thread h(otherthread);
printf("Hello from the first thread\n");
event.Set();
h.join();
}
आउटपुट:
Hello from the first thread
Hello from other thread!
अद्यतन
नीचे tobsen कि AutoResetEvent
नोट टिप्पणियों मेंके बजाय signal_.notify_all()
का अर्थशास्त्र हैमैंने कोड नहीं बदला है क्योंकि accepted answer to the first questionpthread_cond_signal
pthread_cond_broadcast
के विपरीत उपयोग किया गया था और मैं इस बयान के साथ आगे बढ़ रहा हूं कि यह उस उत्तर का एक वफादार अनुवाद है।
स्रोत
2011-12-16 18:45:46
धन्यवाद! यह एक बहुत स्पष्ट व्याख्या थी! :) – derekhh
वास्तव में, अगर प्रतीक्षाऑन से पहले सेट निष्पादित किया गया है (जैसा कि इस उत्तर में जुड़े प्रश्न के उत्तर में बताया गया है) –
ठीक काम करता है, तो डेडलॉक उत्पन्न कर सकता है। 'Bool flag_' के लिए deadlocks का कोई मौका नहीं है और [std :: unique_lock'] के साथ कैसे काम करता है (http://en.cppreference.com/w/cpp/thread/condition_variable/wait)। –