2011-12-16 17 views
7

मैं समझता हूँ कि मैं इस सवाल से पहले कहा है: What is the C++ equivalent for AutoResetEvent under Linux?क्या C++ 0x में AutoResetEvent को लागू करने का कोई आसान तरीका है?

हालांकि, मैं सीख रहा हूँ कि C++ 0x में, थ्रेडिंग पुस्तकालय बहुत सरल बना रहे हैं, तो मैं बाहर फिर से यह सवाल खड़ा करना चाहते हैं, वहाँ है C++ 0x में AutoResetEvent को लागू करने का एक आसान तरीका?

उत्तर

12

यहाँ सी ++ 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_signalpthread_cond_broadcast के विपरीत उपयोग किया गया था और मैं इस बयान के साथ आगे बढ़ रहा हूं कि यह उस उत्तर का एक वफादार अनुवाद है।

+0

धन्यवाद! यह एक बहुत स्पष्ट व्याख्या थी! :) – derekhh

+1

वास्तव में, अगर प्रतीक्षाऑन से पहले सेट निष्पादित किया गया है (जैसा कि इस उत्तर में जुड़े प्रश्न के उत्तर में बताया गया है) –

+0

ठीक काम करता है, तो डेडलॉक उत्पन्न कर सकता है। 'Bool flag_' के लिए deadlocks का कोई मौका नहीं है और [std :: unique_lock'] के साथ कैसे काम करता है (http://en.cppreference.com/w/cpp/thread/condition_variable/wait)। –

संबंधित मुद्दे