void TimeoutManager::Timeouts::Insert(Timeout* aTimeout, SortBy aSortBy) { // Start at mLastTimeout and go backwards. Stop if we see a Timeout with a // valid FiringId since those timers are currently being processed by // RunTimeout. This optimizes for the common case of insertion at the end. Timeout* prevSibling; for (prevSibling = GetLast(); prevSibling && // This condition needs to match the one in SetTimeoutOrInterval that // determines whether to set When() or TimeRemaining(). (aSortBy == SortBy::TimeRemaining ? prevSibling->TimeRemaining() > aTimeout->TimeRemaining() : prevSibling->When() > aTimeout->When()) && // Check the firing ID last since it will evaluate true in the vast // majority of cases. mManager.IsInvalidFiringId(prevSibling->mFiringId); prevSibling = prevSibling->getPrevious()) { /* Do nothing; just searching */ } // Now link in aTimeout after prevSibling. if (prevSibling) { prevSibling->setNext(aTimeout); } else { InsertFront(aTimeout); } aTimeout->mFiringId = InvalidFiringId; }
bool Rcu_data::do_batch() { int count = 0; bool need_resched = false; for (Rcu_list::Const_iterator l = _d.begin(); l != _d.end();) { Rcu_item *i = *l; ++l; need_resched |= i->_call_back(i); ++count; } // XXX: I do not know why this and the former stuff is w/o cpu lock // but the couting needs it ? _d.clear(); // XXX: we use clear, we seemingly worked through the whole list //_d.head(l); { auto guard = lock_guard(cpu_lock); _len -= count; } #if 0 if (_d.full()) { Timeout *t = &_rcu_timeout.cpu(_cpu); t->set(t->get_timeout(0) + Rcu::Period, _cpu); } #endif return need_resched; }
/** * Application setup */ void setup() { bcu.begin(4, 0x7054, 2); // We are a "Jung 2118" device, version 0.2 pinMode(PIO_LED, OUTPUT); digitalWrite(PIO_LED, 1); // Configure the input pins and initialize the debouncers with the current // value of the pin. for (int channel = 0; channel < NUM_CHANNELS; ++channel) { pinMode(inputPins[channel], INPUT | HYSTERESIS | PULL_UP); inputDebouncer[channel].init(digitalRead(inputPins[channel])); } // Handle configured power-up delay unsigned int startupTimeout = calculateTime ( userEeprom[EE_BUS_RETURN_DELAY_BASE] >> 4 , userEeprom[EE_BUS_RETURN_DELAY_FACT] & 0x7F ); Timeout delay; int debounceTime = userEeprom[EE_INPUT_DEBOUNCE_TIME] >> 1; delay.start(startupTimeout); while (delay.started() && !delay.expired()) { // while we wait for the power on delay to expire we debounce the input channels for (int channel = 0; channel < NUM_CHANNELS; ++channel) { inputDebouncer[channel].debounce(digitalRead(inputPins[channel]), debounceTime); } waitForInterrupt(); } initApplication(); }
void BLE::callDispatcher() { // process the external event queue _event_queue.process(); _last_update_us += (uint64_t)_timer.read_high_resolution_us(); _timer.reset(); uint64_t last_update_ms = (_last_update_us / 1000); wsfTimerTicks_t wsf_ticks = (last_update_ms / WSF_MS_PER_TICK); if (wsf_ticks > 0) { WsfTimerUpdate(wsf_ticks); _last_update_us -= (last_update_ms * 1000); } wsfOsDispatcher(); static Timeout nextTimeout; CriticalSectionLock critical_section; if (wsfOsReadyToSleep()) { // setup an mbed timer for the next Cordio timeout bool_t pTimerRunning; timestamp_t nextTimestamp = (timestamp_t) (WsfTimerNextExpiration(&pTimerRunning) * WSF_MS_PER_TICK) * 1000; if (pTimerRunning) { nextTimeout.attach_us(timeoutCallback, nextTimestamp); } } }
void LoaderQueue::startLoader() { LYXERR(Debug::GRAPHICS, "LoaderQueue: waking up"); running_ = true ; timer.setTimeout(s_millisecs_); timer.start(); }
void TimeoutManager::Timeouts::Insert(Timeout* aTimeout, SortBy aSortBy) { // Start at mLastTimeout and go backwards. Don't go further than insertion // point, though. This optimizes for the common case of insertion at the end. Timeout* prevSibling; for (prevSibling = GetLast(); prevSibling && prevSibling != InsertionPoint() && // This condition needs to match the one in SetTimeoutOrInterval that // determines whether to set When() or TimeRemaining(). (aSortBy == SortBy::TimeRemaining ? prevSibling->TimeRemaining() > aTimeout->TimeRemaining() : prevSibling->When() > aTimeout->When()); prevSibling = prevSibling->getPrevious()) { /* Do nothing; just searching */ } // Now link in aTimeout after prevSibling. if (prevSibling) { prevSibling->setNext(aTimeout); } else { InsertFront(aTimeout); } aTimeout->mFiringDepth = 0; // Increment the timeout's reference count since it's now held on to // by the list aTimeout->AddRef(); }
// static VOID CALLBACK Timeout::slot_timeout_win32( HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime ) { Timeout* timeout = s_timeouts[ idEvent ]; if( timeout != NULL ){ timeout->slot_timeout_callback(); } }
void Timeout::check() { while (list && list->time <= rdtsc()) { Timeout *t = list; t->dequeue(); t->trigger(); } }
Timeout *Ev::BusDispatcher::add_timeout(Timeout::Internal *wi) { Timeout *t = new Ev::BusTimeout(wi, _loop, _priority); debug_log("ev: added timeout %p (%s)", t, t->enabled() ? "on" : "off"); return t; }
Timeout *Ecore::BusDispatcher::add_timeout(Timeout::Internal *wi) { Timeout *t = new Ecore::BusTimeout(wi); debug_log("ecore: added timeout %p (%s)", t, t->enabled() ? "on" : "off"); return t; }
inline int mypoll(MYPOLLFD *fds, unsigned int nfds, Timeout timeout){ fd_set readfd; FD_ZERO(&readfd); fd_set writefd; FD_ZERO(&writefd); fd_set oobfd; FD_ZERO(&oobfd); SOCKET maxfd = 0; for (unsigned int i = 0; i < nfds; i++) { if (fds[i].events & POLLIN) { FD_SET(fds[i].fd, &readfd); } if (fds[i].events & POLLOUT) { FD_SET(fds[i].fd, &writefd); } if (fds[i].events & POLLPRI) { FD_SET(fds[i].fd, &oobfd); } fds[i].revents = 0; if (fds[i].fd > maxfd) { maxfd = fds[i].fd; } } struct timeval tv; tv.tv_sec = timeout.getSeconds(); tv.tv_usec = timeout.getMilliseconds() - (timeout.getSeconds() * 1000); int num = select(((int)(maxfd)) + 1, &readfd, &writefd, &oobfd, &tv); if (num < 1) { return num; } for (unsigned int i = 0; i < nfds; i++) { if (FD_ISSET(fds[i].fd, &readfd)) { fds[i].revents |= POLLIN; } if (FD_ISSET(fds[i].fd, &writefd)) { fds[i].revents |= POLLOUT; } if (FD_ISSET(fds[i].fd, &oobfd)) { fds[i].revents |= POLLPRI; } } return num; }
void updateMotors() { if(motor1) to1.attach(&shot1,0.2); if(motor2) to2.attach(&shot2,.2); if(motor3) to3.attach(&shot3,.2); if(motor4) to4.attach(&shot4,.2); //if(motor5) to5.attach(&shot5,.2); if(motor6) to6.attach(&shot6,.2); }
int main() { led1 = 0; led2 = 0; to1.attach_us(led1_on, 1000000); to2.attach_us(led2_on, 2000000); while (1) { printf("Entering sleep.\n"); sleep(); } }
void TimeoutManager::ClearTimeout(int32_t aTimerId, Timeout::Reason aReason) { uint32_t timerId = (uint32_t)aTimerId; bool firstTimeout = true; bool deferredDeletion = false; ForEachUnorderedTimeoutAbortable([&](Timeout* aTimeout) { MOZ_LOG(gLog, LogLevel::Debug, ("Clear%s(TimeoutManager=%p, timeout=%p, aTimerId=%u, ID=%u, tracking=%d)\n", aTimeout->mIsInterval ? "Interval" : "Timeout", this, aTimeout, timerId, aTimeout->mTimeoutId, int(aTimeout->mIsTracking))); if (aTimeout->mTimeoutId == timerId && aTimeout->mReason == aReason) { if (aTimeout->mRunning) { /* We're running from inside the aTimeout. Mark this aTimeout for deferred deletion by the code in RunTimeout() */ aTimeout->mIsInterval = false; deferredDeletion = true; } else { /* Delete the aTimeout from the pending aTimeout list */ aTimeout->remove(); } return true; // abort! } firstTimeout = false; return false; }); // We don't need to reschedule the executor if any of the following are true: // * If the we weren't cancelling the first timeout, then the executor's // state doesn't need to change. It will only reflect the next soonest // Timeout. // * If we did cancel the first Timeout, but its currently running, then // RunTimeout() will handle rescheduling the executor. // * If the window has become suspended then we should not start executing // Timeouts. if (!firstTimeout || deferredDeletion || mWindow.IsSuspended()) { return; } // Stop the executor and restart it at the next soonest deadline. mExecutor->Cancel(); OrderedTimeoutIterator iter(mNormalTimeouts, mTrackingTimeouts); Timeout* nextTimeout = iter.Next(); if (nextTimeout) { MOZ_ALWAYS_SUCCEEDS(MaybeSchedule(nextTimeout->When())); } }
void app_start(int, char*[]) { MBED_HOSTTEST_TIMEOUT(10); MBED_HOSTTEST_SELECT(default_auto); MBED_HOSTTEST_DESCRIPTION(Sleep Timeout); MBED_HOSTTEST_START("MBED_9"); led1 = 0; led2 = 0; led1_initial = led1; led2_initial = led2; to1.attach_us(led1_on, 1000000); to2.attach_us(led2_on, 2000000); }
void BLE::waitForEvent() { static Timeout nextTimeout; timestamp_t nextTimestamp; bool_t pTimerRunning; callDispatcher(); if (wsfOsReadyToSleep()) { // setup an mbed timer for the next cordio timeout nextTimestamp = (timestamp_t)(WsfTimerNextExpiration(&pTimerRunning) * WSF_MS_PER_TICK) * 1000; if (pTimerRunning) { nextTimeout.attach_us(timeoutCallback, nextTimestamp); } } }
void beep(float freq, float time) { buzzer.period(1.0 / freq); buzzer.write(0.5); toff.attach(nobeep, time); led = 0; }
// this is our function that plays a tone. // Takes in a tone frequency, and after duration (in ms.) we stop playing again static void play_tone(int tone, int duration) { buzzer.period_us(tone); buzzer.write(0.10f); // 10% duty cycle, otherwise it's too loud // we wait for duration ms. and then call the silence function tone_timeout.attach_us(&silence, duration*1000); // setup tone_timeout to call silence after duration ms }
//Creates the gyro using given input and calibrates asynchronously it over 2 seconds. Gyro::Gyro(PinName input): _input(input){ _isOn = false; degrees = 0; nullVoltage = 0.7576; gyroTimeOut.attach(this, &Gyro::calibrate, 1.0); //Delays 1 second before actually calibrating }
GameOver::GameOver(Game * _game, float _score) : MY_Scene_Base(_game), done(false) { std::string pic = "ENDING_"; if(_score > 300){ pic += "5"; }else if(_score > 200){ pic += "4"; }else if(_score > 125){ pic += "3"; }else if(_score > 50){ pic += "2"; }else{ pic += "1"; } { VerticalLinearLayout * vl = new VerticalLinearLayout(uiLayer->world); uiLayer->addChild(vl); vl->setRationalHeight(1.f, uiLayer); vl->setRationalWidth(1.f, uiLayer); vl->horizontalAlignment = kCENTER; vl->verticalAlignment = kMIDDLE; NodeUI * menu = new NodeUI(uiLayer->world); vl->addChild(menu); menu->setRationalHeight(1.f, vl); menu->setSquareWidth(1.f); menu->background->mesh->pushTexture2D(MY_ResourceManager::globalAssets->getTexture(pic)->texture); menu->background->mesh->setScaleMode(GL_NEAREST); } Timeout * doneTimeout = new Timeout(0.5f, [this](sweet::Event * _event){ done = true; NodeUI * n = new NodeUI(uiLayer->world); n->setRationalHeight(1.f, uiLayer); n->setRationalWidth(1.f, uiLayer); uiLayer->addChild(n); n->background->mesh->pushTexture2D(MY_ResourceManager::globalAssets->getTexture("CLICK")->texture); n->background->mesh->setScaleMode(GL_NEAREST); }); doneTimeout->start(); doneTimeout->name = "done timeout"; childTransform->addChild(doneTimeout, false); }
virtual long set_timeout(size_t time, function<void ()> callback) { if(log_level) std::cerr << "BlockwiseImpl::set_timeout" << std::endl; timeout.set(time,callback); return 0; }
bool ThreadSleeper::sleep(Timeout timeout) { if (timeout.isInfinite()) { sem_wait(&semaphore); } else { timespec tmspc = timeout.getExpireTime().getTimeSpec(); int res = sem_timedwait(&semaphore,&tmspc); if (res == -1) { int e = errno; if (e == ETIMEDOUT) return true; if (e != EINTR) throw ErrNoException(THISLOCATION,e); //Consider EINTR as wakeUp return false; } } while (sem_trywait(&semaphore) == 0) {} return false; }
void TimeoutManager::UpdateBackgroundState() { mExecutionBudget = GetMaxBudget(mWindow.IsBackgroundInternal()); // When the window moves to the background or foreground we should // reschedule the TimeoutExecutor in case the MinSchedulingDelay() // changed. Only do this if the window is not suspended and we // actually have a timeout. if (!mWindow.IsSuspended()) { OrderedTimeoutIterator iter(mNormalTimeouts, mTrackingTimeouts); Timeout* nextTimeout = iter.Next(); if (nextTimeout) { mExecutor->Cancel(); MOZ_ALWAYS_SUCCEEDS(MaybeSchedule(nextTimeout->When())); } } }
void TimeoutManager::Resume() { MOZ_LOG(gLog, LogLevel::Debug, ("Resume(TimeoutManager=%p)\n", this)); // When Suspend() has been called after IsDocumentLoaded(), but the // throttle tracking timer never managed to fire, start the timer // again. if (mWindow.AsInner()->IsDocumentLoaded() && !mThrottleTimeouts) { MaybeStartThrottleTimeout(); } OrderedTimeoutIterator iter(mNormalTimeouts, mTrackingTimeouts); Timeout* nextTimeout = iter.Next(); if (nextTimeout) { MOZ_ALWAYS_SUCCEEDS(MaybeSchedule(nextTimeout->When())); } }
int main() { Threat threat = Threat(0); Timeout loopTimeout = Timeout(40); // game loop while (1) { loopTimeout.start(); string enemy1; // name of enemy 1 cin >> enemy1; cin.ignore(); int dist1; // distance to enemy 1 cin >> dist1; cin.ignore(); threat.push_back(Enemy(dist1, enemy1)); string enemy2; // name of enemy 2 cin >> enemy2; cin.ignore(); int dist2; // distance to enemy 2 cin >> dist2; cin.ignore(); threat.push_back(Enemy(dist2, enemy2)); // We have acquired the list of enemy // We have to sort the list from the // closest to far away sort(threat.begin(), threat.end(), [](const Enemy & a, const Enemy & b) { // true will make the sort to let // the object in the same order return a.getDist() < b.getDist(); }); // We acquire the enemy which is the closer, // ie at the end of the list of threat Enemy threatToEliminate = threat.front(); threat.erase(threat.begin()); // We output the enemy to kill cout << threatToEliminate.getName() << endl; if(loopTimeout.hasTimedOut()) break; } return EXIT_SUCCESS; }
int main() { printf("Hello world!\n"); printf("LED1 will blink every second, LED3 will toggle after 2.5 seconds, LED2 can be toggled through BUTTON1.\n"); printf("-----------------------------------\n\n"); t1.attach(callback(&blink_led1), 1.0f); t2.attach(callback(&turn_led3_on), 2.5f); btn.fall(callback(&toggle_led2)); wait_ms(osWaitForever); }
bool equeue_sema_wait(equeue_sema_t *s, int ms) { int signal = 0; Timeout timeout; if (ms > 0) { timeout.attach_us(callback(equeue_sema_timeout, s), ms*1000); } core_util_critical_section_enter(); while (!*s) { sleep(); core_util_critical_section_exit(); core_util_critical_section_enter(); } signal = *s; *s = false; core_util_critical_section_exit(); return (signal > 0); }
void toggleOn (void) { static int toggle_counter = 0; out = 1; led = 1; if (toggle_counter == MS_INTERVALS) { print_char(); toggle_counter = 0; } toggle_counter++; timer.attach_us(toggleOff, 500); }
virtual void initialize() { // We retry zookeeper_init until the timeout elapses because we've // seen cases where temporary DNS outages cause the slave to abort // here. See MESOS-1326 for more information. // ZooKeeper masks EAI_AGAIN as EINVAL and a name resolution timeout // may be upwards of 30 seconds. As such, a 10 second timeout is not // enough. Hard code this to 10 minutes to be sure we're trying again // in the face of temporary name resolution failures. See MESOS-1523 // for more information. const Timeout timeout_ = Timeout::in(Minutes(10)); while (!timeout_.expired()) { zh = zookeeper_init( servers.c_str(), event, static_cast<int>(timeout.ms()), NULL, &callback, 0); // Unfortunately, EINVAL is highly overloaded in zookeeper_init // and can correspond to: // (1) Empty / invalid 'host' string format. // (2) Any getaddrinfo error other than EAI_NONAME, // EAI_NODATA, and EAI_MEMORY are mapped to EINVAL. // Either way, retrying is not problematic. if (zh == NULL && errno == EINVAL) { ErrnoError error("zookeeper_init failed"); LOG(WARNING) << error.message << " ; retrying in 1 second"; os::sleep(Seconds(1)); continue; } break; } if (zh == NULL) { PLOG(FATAL) << "Failed to create ZooKeeper, zookeeper_init"; } }
void updateTimeouts() { time_t now = World::instance()->time(); bool next = true; while (next && timeouts.size()) { Timeout* t = timeouts.front(); if (!t->isActive()) { timeouts.pop_front(); delete t; } else if (t->ready(now)) { t->execute(); timeouts.pop_front(); delete t; } else { next = false; } } }