How to implementing a conditional wait
Hi, I have to do a simple task, but I'm quite confused. I have a class that sends some data on RS232 and wait for a answer. (What in Windows is WaitForSingleObject) void ATDispatcher::OnDataReveived() { // Data received from RS232 serial_port.GetData(&buffer); boost::lock_guardboost::mutex lock(mut); data_ready = true; cond.notify_one(); }; void ATDispatcher::AtDispatcher(SerialPort& device) : _device(device) { // Connecting the slot for receiving event _device.OnData(boost::bind(&ATDispatcher::OnDataReceived(), &this)); }; int ATDispatcher::SendCommand(std::string cmd, bool waitOK = true, bool decode_answer = true int cmd_timeout = COMMAND_TIMEOUT) { boost::unique_lockboost::mutex lock(mut); boost::xtime xt; xtime_get(&xt,boost::TIME_UTC); xt.sec += cmd_timeout; data_ready = false; //Send data.... while(!data_ready) { cond.timed_wait(lock, xt); } }; Ok, The OnDataReceived is called from the SerialPort thread when the data is available. In the SendCommand I have to wait for a timeout or until the answer is arrived...how can I do it? Thanks! Daniele.
AMDG Daniele Barzotti wrote:
while(!data_ready) { cond.timed_wait(lock, xt); }
Ok, The OnDataReceived is called from the SerialPort thread when the data is available. In the SendCommand I have to wait for a timeout or until the answer is arrived...how can I do it?
Use the predicate form of timed_wait. bool ready = cond.timed_wait(lock, xt, boost::lambda::var(data_ready)); In Christ, Steven Watanabe
participants (2)
-
Daniele Barzotti
-
Steven Watanabe