Ecco una traduzione del accepted answer to your first question da utilizzare C++ 11 strumenti:
#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();
}
uscita:
Hello from the first thread
Hello from other thread!
Aggiornamento
nei commenti qui sotto tobsen note AutoResetEvent
ha la semantica di signal_.notify_all()
anziché signal_.notify_one()
. Non ho modificato il codice perché il accepted answer to the first question utilizzato pthread_cond_signal
in contrasto con pthread_cond_broadcast
e sto conducendo con la dichiarazione che questa è una traduzione fedele di quella risposta.
fonte
2011-12-16 18:45:46
Grazie! Questa è stata un'interpretazione molto chiara! :) – derekhh
Infatti, è in grado di produrre un deadlock se Set viene eseguito prima di WaitOne (come spiegato nella risposta alla domanda collegata in questa risposta) –
Funziona correttamente. Nessuna possibilità di deadlock grazie a 'bool flag_' e [come' wait() 'funziona con' std :: unique_lock'] (http://en.cppreference.com/w/cpp/thread/condition_variable/wait). –