Archived

This forum has been archived. Please start a new discussion on GitHub.

ICE Cond cannot wait after signal

hi, master, I have a small question for ICE Cond. The sample code as below:
I signal a cond variable twice in MyThread and expect I can wait this cond twice in main() function.
But seems the sample code does not run as my experience. Program blocked in second cond.wait(). Could you please give any suggestion about, Is this the right behavior? Thanks very much.

#include <iostream>
#include <IceUtil/Thread.h>
#include <IceUtil/Cond.h>

using namespace std;
using namespace IceUtil;

Mutex mutex;
Cond cond;

class MyThread : public Thread
{
public:
virtual void run()
{
Mutex::Lock lock(mutex);
cout << "In function " << __FUNCTION__ << " singled with tid " <<
this->getThreadControl().id() << endl;
cond.signal();
cond.signal();
}
};

int main()
{
ThreadPtr thread = new MyThread();
thread->start();

// wait for thread execute
{
Mutex::Lock lock(mutex);
cond.wait(lock);
}
cout << "Cond wait in function " << __FUNCTION__ << endl;

Sleep(1000);

{
// wait twice
Mutex::Lock lock(mutex);
cond.wait(lock);
}

cout << "Cond wait in function " << __FUNCTION__ << endl;

thread->getThreadControl().join();
return 0;
}

Comments

  • bernard
    bernard Jupiter, FL
    The IceUtil thread & synchronization classes are for the most part a thin portability layer on top of POSIX and Windows primitives, such as threads, mutexes and condition variables.

    When you signal a condition variable, the signal is sent immediately - it's not queued - so your second cond.wait() will block since the second signal was most likely sent before your main thread got there.

    If you are looking for a good book on this topic, I recommend David Butenhof's Programming with POSIX Threads.

    Then, while you can of course use IceUtil thread & synchronization classes, there is now a better alternative with C++11; I'd suggest to use std::condition_variable instead of IceUtil::Cond.

    Best regards,
    Bernard
  • Dear Bernard:
    Thanks for your teaching, it helps me too much.

    Sincerely