I am going to use timed_wait() from boost to wait for conditional variable. I couldn't find out good peace code from boost documentation and found some stack overflow references. in those examples, I found following 2 uses.
bool bDoneInTime = g_Condition.timed_wait(lockedCondLock, boost::system_time() + boost::posix_time::seconds(1));passing the delay with adding it into system time.bool bDoneInTime = g_Condition.timed_wait(lockedCondLock, boost::posix_time::seconds(1));just pass the delay
I tried both in following sample code just for testing
#include <string>
#include <vector>
#include <iostream>
#include <thread>
#include <time.h>
#include <sys/time.h>
#include <pthread.h>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition_variable.hpp>
static boost::mutex g_ConditionMutex;
typedef boost::unique_lock<boost::mutex> lock_t;
static boost::condition_variable g_Condition;
using namespace std;
void* fun(void* arg)
{
printf("\nIn thread\n");
lock_t lock(g_ConditionMutex);
printf("Sleep second\n");
g_Condition.timed_wait(lock, boost::posix_time::seconds(1));
printf("Sleep second as zebra driver\n");
g_Condition.timed_wait(lock, boost::system_time() + boost::posix_time::seconds(1));
printf("\nDone\n");
}
int main(int argc, char *argv[])
{
pthread_t thread;
void *ret;
pthread_create(&thread, NULL, fun, NULL);
printf("Sleep 10 sec main\n");
sleep(10);
printf("Notify\n");
g_Condition.notify_one();
pthread_join(thread,&ret);
return 0;
}
both methods are working but I am confused with how to use this template<typename lock_type> bool timed_wait(lock_type& lock,boost::system_time const& abs_time) from boost.
Please someone help me to figure out the correct way.