एक AutoResetEvent एक बाइनरी सेमाफोर करने के लिए सबसे समान है। लोग कहते हैं कि "सशर्त चर" गलत नहीं हैं, लेकिन इसी तरह की स्थितियों के बजाय, समान परिस्थितियों में हालत चर का उपयोग किया जाता है। आप शर्त चर के शीर्ष पर एक (बेनाम) AutoResetEvent लागू कर सकते हैं:
#include <pthread.h>
#include <stdio.h>
class AutoResetEvent
{
public:
explicit AutoResetEvent(bool initial = false);
~AutoResetEvent();
void Set();
void Reset();
bool WaitOne();
private:
AutoResetEvent(const AutoResetEvent&);
AutoResetEvent& operator=(const AutoResetEvent&); // non-copyable
bool flag_;
pthread_mutex_t protect_;
pthread_cond_t signal_;
};
AutoResetEvent::AutoResetEvent(bool initial)
: flag_(initial)
{
pthread_mutex_init(&protect_, NULL);
pthread_cond_init(&signal_, NULL);
}
void AutoResetEvent::Set()
{
pthread_mutex_lock(&protect_);
flag_ = true;
pthread_mutex_unlock(&protect_);
pthread_cond_signal(&signal_);
}
void AutoResetEvent::Reset()
{
pthread_mutex_lock(&protect_);
flag_ = false;
pthread_mutex_unlock(&protect_);
}
bool AutoResetEvent::WaitOne()
{
pthread_mutex_lock(&protect_);
while(!flag_) // prevent spurious wakeups from doing harm
pthread_cond_wait(&signal_, &protect_);
flag_ = false; // waiting resets the flag
pthread_mutex_unlock(&protect_);
return true;
}
AutoResetEvent::~AutoResetEvent()
{
pthread_mutex_destroy(&protect_);
pthread_cond_destroy(&signal_);
}
AutoResetEvent event;
void *otherthread(void *)
{
event.WaitOne();
printf("Hello from other thread!\n");
return NULL;
}
int main()
{
pthread_t h;
pthread_create(&h, NULL, &otherthread, NULL);
printf("Hello from the first thread\n");
event.Set();
pthread_join(h, NULL);
return 0;
}
यदि फिर भी, आप स्वत: रीसेट घटनाओं नामित की जरूरत है, आप की संभावना सेमाफोर को देखने के लिए चाहता हूँ, और एक से थोड़ा अधिक कठिन समय अनुवाद हो सकता है तुम्हारा कोड। किसी भी तरह से मैं आपके प्लेटफ़ॉर्म पर पर्थ्रेड के लिए प्रलेखन पर सावधान रहूंगा, हालत चर और ऑटो रीसेट ईवेंट समान नहीं हैं और वही व्यवहार नहीं करते हैं।
स्रोत
2011-11-14 22:21:40
नहीं, यह बिल्कुल म्यूटेक्स की तरह नहीं है। यह एक शर्त चर की तरह है। – Gabe