void do_test(void (this_type::*test_func)()) { Lock lock(m); locked=false; done=false; boost::thread t(test_func,this); try { { boost::mutex::scoped_lock lk(done_mutex); BOOST_CHECK(!done_cond.timed_wait(lk, boost::posix_time::seconds(1), boost::bind(&this_type::is_done,this))); } lock.unlock(); { boost::mutex::scoped_lock lk(done_mutex); BOOST_CHECK(done_cond.timed_wait(lk, boost::posix_time::seconds(1), boost::bind(&this_type::is_done,this))); } t.join(); BOOST_CHECK(locked); } catch(...) { lock.unlock(); t.join(); throw; } }
int main() { #if defined(BOOST_THREAD_PLATFORM_PTHREAD) for (int i=0; i<3; ++i) { const time_t now_time = ::time(0); const time_t wait_time = now_time+1; time_t end_time; assert(now_time < wait_time); boost::unique_lock<boost::mutex> lk(mtx); //const bool res = (void)cv.timed_wait(lk, from_time_t(wait_time)); end_time = ::time(0); std::cerr << "now_time =" << now_time << " \n"; std::cerr << "end_time =" << end_time << " \n"; std::cerr << "wait_time=" << wait_time << " \n"; std::cerr << "now_time =" << from_time_t(now_time) << " \n"; std::cerr << "end_time =" << from_time_t(end_time) << " \n"; std::cerr << "wait_time=" << from_time_t(wait_time) << " \n"; std::cerr << end_time - wait_time << " \n"; assert(end_time >= wait_time); std::cerr << " OK\n"; } #endif return 0; }
void operator()() { Lock lock(m); typedef test_initially_unlocked_if_other_thread_has_lock<Mutex,Lock> this_type; boost::thread t(&this_type::locking_thread,this); try { { boost::mutex::scoped_lock lk(done_mutex); BOOST_CHECK(done_cond.timed_wait(lk,boost::posix_time::seconds(2), boost::bind(&this_type::is_done,this))); BOOST_CHECK(!locked); } lock.unlock(); t.join(); } catch(...) { lock.unlock(); t.join(); throw; } }
void relative_timed_wait_with_predicate() { boost::unique_lock<boost::mutex> lock(mutex); if(cond_var.timed_wait(lock,boost::posix_time::seconds(timeout_seconds),check_flag(flag)) && flag) { ++woken; } }
bool timedWaitOnMutex(boost::condition_variable &waitCond, boost::mutex &waitMutex, int secs, int msecs) { boost::posix_time::ptime waitTime(boost::posix_time::microsec_clock::universal_time()); waitTime += boost::posix_time::seconds(secs); waitTime += boost::posix_time::millisec(msecs); boost::unique_lock<boost::mutex> lock(waitMutex); return waitCond.timed_wait(lock, waitTime) == false; }
void timed_wait_with_predicate() { boost::system_time const timeout=boost::get_system_time()+boost::posix_time::seconds(timeout_seconds); boost::unique_lock<boost::mutex> lock(mutex); if(cond_var.timed_wait(lock,timeout,check_flag(flag)) && flag) { ++woken; } }
/*! * The auto flusher ensures that buffers are force committed when * the user has not called get_new() within a certain time window. */ void auto_flush(void) { boost::mutex::scoped_lock lock(_mutex); const bool timeout = not _cond.timed_wait(lock, AUTOFLUSH_TIMEOUT); if (timeout and _ok_to_auto_flush and _last_send_buff and _bytes_in_buffer != 0) { _last_send_buff->commit(_bytes_in_buffer); _last_send_buff.reset(); } }
void do_transaction(int comm_state) { lock_t lock(mtx_); comm_state_ = comm_state; lock.unlock(); my_io_service_.send(tx_); lock.lock(); while(comm_state_!=CST_IDLE){ if(!rx_cond_var_.timed_wait(lock, boost::posix_time::milliseconds(op_timeout_ms_))){ throw OperationTimeoutExcept(); } } }
BOOLEAN timed_wait_and_pop ( Data& value, INT64 millsec ) { boost::system_time const timeout=boost::get_system_time() + boost::posix_time::milliseconds(millsec); boost::mutex::scoped_lock lock ( _mutex ) ; while ( _queue.empty () ) if ( !_cond.timed_wait ( lock, timeout ) ) return FALSE ; value = _queue.front () ; _queue.pop () ; return TRUE ; }
void timed_wait_without_predicate() { boost::system_time const timeout=boost::get_system_time()+boost::posix_time::seconds(timeout_seconds); boost::unique_lock<boost::mutex> lock(mutex); while(!flag) { if(!cond_var.timed_wait(lock,timeout)) { return; } } ++woken; }
bool timed_wait(Duration d) { boost::system_time const target=boost::get_system_time()+d; boost::unique_lock<boost::mutex> l(m); while(!flag) { if(!cond.timed_wait(l,target)) { return flag; } } return true; }
int wait(const boost::system_time& wait_until_abs_time, int* old_val = NULL) { #if 0 if (old_val && *old_val != m_count) { *old_val = m_count; return 0; } #endif scoped_lock g(m_lock); try { return m_cond.timed_wait(g, wait_until_abs_time) ? 0 : ETIMEDOUT; } catch (std::exception&) { return -1; } }
bool timed_lock_shared(system_time const& timeout) { boost::this_thread::disable_interruption do_not_disturb; boost::mutex::scoped_lock lk(state_change); while(state.exclusive || state.exclusive_waiting_blocked) { if(!shared_cond.timed_wait(lk,timeout)) { return false; } } ++state.shared_count; return true; }
/** * Worker thread proc for Timer objects. */ void Timer::TimerThreadProc(void) { Utility::SetThreadName("Timer Thread"); for (;;) { boost::mutex::scoped_lock lock(l_Mutex); typedef boost::multi_index::nth_index<TimerSet, 1>::type NextTimerView; NextTimerView& idx = boost::get<1>(l_Timers); /* Wait until there is at least one timer. */ while (idx.empty() && !l_StopThread) l_CV.wait(lock); if (l_StopThread) break; NextTimerView::iterator it = idx.begin(); Timer::Ptr timer = it->lock(); if (!timer) { /* Remove the timer from the list if it's not alive anymore. */ idx.erase(it); continue; } double wait = timer->m_Next - Utility::GetTime(); if (wait > 0) { /* Make sure the timer we just examined can be destroyed while we're waiting. */ timer.reset(); /* Wait for the next timer. */ l_CV.timed_wait(lock, boost::posix_time::milliseconds(wait * 1000)); continue; } /* Remove the timer from the list so it doesn't get called again * until the current call is completed. */ l_Timers.erase(timer); lock.unlock(); /* Asynchronously call the timer. */ Utility::QueueAsyncCallback(boost::bind(&Timer::Call, timer)); } }
bool wait_and_pop(T& data, boost::posix_time::microseconds waitTime) { boost::system_time timeout = boost::get_system_time() + waitTime; boost::mutex::scoped_lock lockHandle(mutexHandle); if (condFlag.timed_wait(lockHandle, timeout, isEmpty(&queueHandle))) { data = queueHandle.front(); queueHandle.pop(); condFlag.notify_all(); return true; } else { return false; } }
bool detectFiducialsServiceCallback(cob_object_detection_msgs::DetectObjects::Request &req, cob_object_detection_msgs::DetectObjects::Response &res) { ROS_DEBUG("[fiducials] Service Callback"); // Connect to image topics bool result = false; synchronizer_received_ = false; connectCallback(); // Wait for data { boost::mutex::scoped_lock lock( mutexQ_); boost::system_time const timeout=boost::get_system_time()+ boost::posix_time::milliseconds(5000); ROS_INFO("[fiducials] Waiting for image data"); if (condQ_.timed_wait(lock, timeout)) ROS_INFO("[fiducials] Waiting for image data [OK]"); else { ROS_WARN("[fiducials] Could not receive image data from ApproximateTime synchronizer"); return false; } // Wait for data (at least 5 seconds) //int nSecPassed = 0; //float nSecIncrement = 0.5; //while (!synchronizer_received_ && nSecPassed < 10) //{ // ros::Duration(nSecIncrement).sleep(); // nSecPassed += nSecIncrement; // ROS_INFO("[fiducials] Waiting"); //} //if (!synchronizer_received_) //{ // ROS_WARN("[fiducials] Could not receive image data"); // return false; //} result = detectFiducials(res.object_list, color_mat_8U3_); } disconnectCallback(); return result; }
bool timed_lock(system_time const& timeout) { boost::this_thread::disable_interruption do_not_disturb; boost::mutex::scoped_lock lk(state_change); while(state.shared_count || state.exclusive) { state.exclusive_waiting_blocked=true; if(!exclusive_cond.timed_wait(lk,timeout)) { if(state.shared_count || state.exclusive) { state.exclusive_waiting_blocked=false; exclusive_cond.notify_one(); return false; } break; } } state.exclusive=true; return true; }
void CGpio::Do_Work() { int interruptNumber = NO_INTERRUPT; boost::posix_time::milliseconds duration(12000); std::vector<int> triggers; _log.Log(LOG_NORM,"GPIO: Worker started..."); while (!m_stoprequested) { #ifndef WIN32 boost::mutex::scoped_lock lock(interruptQueueMutex); if (!interruptCondition.timed_wait(lock, duration)) { //_log.Log(LOG_NORM, "GPIO: Updating heartbeat"); mytime(&m_LastHeartbeat); } else { while (!gpioInterruptQueue.empty()) { interruptNumber = gpioInterruptQueue.front(); triggers.push_back(interruptNumber); gpioInterruptQueue.erase(gpioInterruptQueue.begin()); _log.Log(LOG_NORM, "GPIO: Acknowledging interrupt for GPIO %d.", interruptNumber); } } lock.unlock(); if (m_stoprequested) { break; } while (!triggers.empty()) { interruptNumber = triggers.front(); triggers.erase(triggers.begin()); CGpio::ProcessInterrupt(interruptNumber); } #else sleep_milliseconds(100); #endif } _log.Log(LOG_NORM,"GPIO: Worker stopped..."); }
void Main::loop(const string & device) { LOG4CPLUS_TRACE_STR(logger, "Main::loop()"); struct sigaction action; action.sa_handler = &Main::signalHandler; action.sa_flags = SA_RESETHAND; sigemptyset(&action.sa_mask); int restart = false; do { /* Get logicalAddress after openning device */ logicalAddress = cec.open(device); LOG4CPLUS_INFO(logger, "Address \"" << logicalAddress << "\""); if ( logicalAddress != CECDEVICE_UNKNOWN) running = true; /* install signals */ sigaction (SIGHUP, &action, NULL); sigaction (SIGINT, &action, NULL); sigaction (SIGTERM, &action, NULL); if (makeActive) { cec.makeActive(); } do { boost::unique_lock<boost::mutex> libcec_lock(libcec_sync); while( running && !commands.empty() ) { Command cmd = commands.front(); switch( cmd.command ) { case COMMAND_STANDBY: if( ! onStandbyCommand.empty() ) { LOG4CPLUS_DEBUG(logger, "Standby: Running \"" << onStandbyCommand << "\""); int ret = system(onStandbyCommand.c_str()); if( ret ) LOG4CPLUS_ERROR(logger, "Standby command failed: " << ret); } else { onCecKeyPress( CEC_USER_CONTROL_CODE_POWER_OFF_FUNCTION ); } break; case COMMAND_ACTIVE: makeActive = true; if( ! onActivateCommand.empty() ) { LOG4CPLUS_DEBUG(logger, "Activated: Running \"" << onActivateCommand << "\""); int ret = system(onActivateCommand.c_str()); if( ret ) LOG4CPLUS_ERROR(logger, "Activate command failed: " << ret); } break; case COMMAND_INACTIVE: makeActive = false; if( ! onDeactivateCommand.empty() ) { LOG4CPLUS_DEBUG(logger, "Deactivated: Running \"" << onDeactivateCommand << "\""); int ret = system(onDeactivateCommand.c_str()); if( ret ) LOG4CPLUS_ERROR(logger, "Deactivate command failed: " << ret); } break; case COMMAND_KEYPRESS: onCecKeyPress( cmd.keycode ); break; case COMMAND_RESTART: running = false; restart = true; break; case COMMAND_EXIT: running = false; break; } commands.pop(); } int retriesRemaining = 3; while( running && !libcec_cond.timed_wait(libcec_lock, boost::posix_time::seconds(43)) ) { // Since libcec's CAdapterPingThread::Process() tries pinging 3 times before raising a // connection lost alert, lets also make 3 attempts otherwise we'll stop running // before our alert handling gets a chance to do its job bool pinged = false; if( retriesRemaining > 0 && !(pinged = cec.ping()) ) { --retriesRemaining; boost::this_thread::sleep(boost::posix_time::milliseconds(CEC_DEFAULT_TRANSMIT_RETRY_WAIT)); } else { running = pinged; } } } while( running ); /* reset signals */ signal (SIGHUP, SIG_DFL); signal (SIGINT, SIG_DFL); signal (SIGTERM, SIG_DFL); cec.close(!restart); } while( restart ); }
void Main::loop(const string & device) { LOG4CPLUS_TRACE_STR(logger, "Main::loop()"); struct sigaction action; action.sa_handler = &Main::signalHandler; action.sa_flags = SA_RESETHAND; sigemptyset(&action.sa_mask); int restart = false; do { cec.open(device); running = true; /* install signals */ sigaction (SIGHUP, &action, NULL); sigaction (SIGINT, &action, NULL); sigaction (SIGTERM, &action, NULL); if (makeActive) { cec.makeActive(); } do { boost::unique_lock<boost::mutex> libcec_lock(libcec_sync); while( running && !commands.empty() ) { Command cmd = commands.front(); switch( cmd.command ) { case COMMAND_STANDBY: if( ! onStandbyCommand.empty() ) { LOG4CPLUS_DEBUG(logger, "Standby: Running \"" << onStandbyCommand << "\""); int ret = system(onStandbyCommand.c_str()); if( ret ) LOG4CPLUS_ERROR(logger, "Standby command failed: " << ret); } else { onCecKeyPress( CEC_USER_CONTROL_CODE_POWER ); } break; case COMMAND_ACTIVE: makeActive = true; if( ! onActivateCommand.empty() ) { LOG4CPLUS_DEBUG(logger, "Activated: Running \"" << onActivateCommand << "\""); int ret = system(onActivateCommand.c_str()); if( ret ) LOG4CPLUS_ERROR(logger, "Activate command failed: " << ret); } break; case COMMAND_INACTIVE: makeActive = false; if( ! onDeactivateCommand.empty() ) { LOG4CPLUS_DEBUG(logger, "Deactivated: Running \"" << onDeactivateCommand << "\""); int ret = system(onDeactivateCommand.c_str()); if( ret ) LOG4CPLUS_ERROR(logger, "Deactivate command failed: " << ret); } break; case COMMAND_KEYPRESS: onCecKeyPress( cmd.keycode ); break; case COMMAND_RESTART: running = false; restart = true; break; case COMMAND_EXIT: running = false; break; } commands.pop(); } while( running && !libcec_cond.timed_wait(libcec_lock, boost::posix_time::seconds(43)) ) { running = cec.ping(); } } while( running ); /* reset signals */ signal (SIGHUP, SIG_DFL); signal (SIGINT, SIG_DFL); signal (SIGTERM, SIG_DFL); cec.close(!restart); } while( restart ); }
static void durThread() { Client::initThread("journal"); bool samePartition = true; try { const std::string dbpathDir = boost::filesystem::path(storageGlobalParams.dbpath).string(); samePartition = onSamePartition(getJournalDir().string(), dbpathDir); } catch(...) { } while (shutdownRequested.loadRelaxed() == 0) { unsigned ms = storageGlobalParams.journalCommitInterval; if( ms == 0 ) { ms = samePartition ? 100 : 30; } unsigned oneThird = (ms / 3) + 1; // +1 so never zero try { stats.rotate(); boost::mutex::scoped_lock lock(flushMutex); // commit sooner if one or more getLastError j:true is pending for (unsigned i = 0; i <= 2; i++) { if (flushRequested.timed_wait(lock, Milliseconds(oneThird))) { // Someone forced a flush break; } if (commitJob._notify.nWaiting()) break; if (commitJob.bytes() > UncommittedBytesLimit / 2) break; } OperationContextImpl txn; // Waits for all active operations to drain and won't let new ones start. This // should be optimized to allow readers in (see SERVER-15262). AutoAcquireFlushLockForMMAPV1Commit flushLock(txn.lockState()); groupCommit(); remapPrivateView(); } catch(std::exception& e) { log() << "exception in durThread causing immediate shutdown: " << e.what() << endl; mongoAbort("exception in durThread"); } catch (...) { log() << "unhandled exception in durThread causing immediate shutdown" << endl; mongoAbort("unhandled exception in durThread"); } } cc().shutdown(); }