size_t Socket::nonblock_recv(std::vector<std::string::value_type> &buf, const std::chrono::milliseconds &timeWait) const { size_t recv_len = ~0; #ifdef WIN32 WSAPOLLFD event = { socket_handle, POLLRDNORM, 0 }; if (1 == ::WSAPoll(&event, 1, timeWait.count() ) && event.revents & POLLRDNORM) { recv_len = ::recv(socket_handle, buf.data(), buf.size(), 0); } #elif POSIX struct ::pollfd event = { socket_handle, POLLIN, 0 }; if (1 == ::poll(&event, 1, timeWait.count() ) && event.revents & POLLIN) { recv_len = ::recv(socket_handle, buf.data(), buf.size(), MSG_NOSIGNAL); } #else #error "Undefine platform" #endif return recv_len; }
long Socket::nonblock_recv(std::vector<std::string::value_type> &buf, const std::chrono::milliseconds &timeout) const { long recv_len = ~0; #ifdef WIN32 WSAPOLLFD event = { this->socket_handle, POLLRDNORM, 0 }; if (1 == ::WSAPoll(&event, 1, static_cast<::INT>(timeout.count() ) ) && event.revents & POLLRDNORM) { recv_len = ::recv(this->socket_handle, buf.data(), static_cast<int>(buf.size() ), 0); } #elif POSIX struct ::pollfd event = { this->socket_handle, POLLIN, 0 }; if (1 == ::poll(&event, 1, timeout.count() ) && event.revents & POLLIN) { recv_len = ::recv(this->socket_handle, buf.data(), buf.size(), 0); } #else #error "Undefine platform" #endif return recv_len; }
size_t Socket::nonblock_send(const std::vector<std::string::value_type> &buf, const size_t length, const std::chrono::milliseconds &timeWait) const { size_t send_len = ~0; #ifdef WIN32 WSAPOLLFD event = { socket_handle, POLLWRNORM, 0 }; if (1 == ::WSAPoll(&event, 1, timeWait.count() ) && event.revents & POLLWRNORM) { send_len = ::send(socket_handle, buf.data(), length, 0); } #elif POSIX struct ::pollfd event = { socket_handle, POLLOUT, 0 }; if (1 == ::poll(&event, 1, timeWait.count() ) && event.revents & POLLOUT) { send_len = ::send(socket_handle, buf.data(), length, MSG_NOSIGNAL); } #else #error "Undefine platform" #endif return send_len; }
bool Piped_request_waiter::Wait(std::chrono::milliseconds timeout) { fd_set rfds; FD_ZERO(&rfds); FD_SET(read_pipe, &rfds); timeval tv = {0, 0}; timeval* tvp = &tv; if (timeout.count() > 0) { /* Calculate full seconds and remainder in microseconds. */ std::chrono::seconds full_sec = std::chrono::duration_cast<std::chrono::seconds>(timeout); tv.tv_sec = full_sec.count(); timeout -= full_sec; tv.tv_usec = std::chrono::microseconds(timeout).count(); } else if (timeout.count() < 0) { tvp = nullptr; } int rc = select(read_pipe + 1, &rfds, nullptr, nullptr, tvp); if (rc == 0) { /* Timeout occurred. */ return false; } else if (rc < 0) { VSM_SYS_EXCEPTION("Wait pipe wait error"); } Ack(); return true; }
Socket Socket::nonblock_accept(const std::chrono::milliseconds &timeWait) const { System::native_socket_type client_socket = ~0; #ifdef WIN32 WSAPOLLFD event = { socket_handle, POLLRDNORM, 0 }; if (1 == ::WSAPoll(&event, 1, timeWait.count() ) && event.revents & POLLRDNORM) { client_socket = ::accept(socket_handle, static_cast<sockaddr *>(nullptr), static_cast<int *>(nullptr) ); } #elif POSIX struct ::pollfd event = { socket_handle, POLLIN, 0 }; if (1 == ::poll(&event, 1, timeWait.count() ) && event.revents & POLLIN) { client_socket = ::accept(socket_handle, static_cast<sockaddr *>(nullptr), static_cast<socklen_t *>(nullptr) ); } #else #error "Undefine platform" #endif return Socket(client_socket); }
int main(int argc, char* argv[]) { std::string receivingInterfaceFilter; if(argc>1) { if(std::string(argv[1])=="-h") { std::cout << "Listens on incoming announces for a specific time. Returns a compact format about all received announcements." << std::endl; std::cout << "syntax: " << argv[0] << " <interface name>" << std::endl; std::cout << "return format: <family type> <uuid> <type> <name> <address> <netmask> <http port> <interface address> <interface netmask>" << std::endl; return 0; } else { receivingInterfaceFilter = argv[1]; } } static const std::chrono::milliseconds timeToWait(10000); hbm::devscan::Receiver receiver; std::cerr << "Collecting announcements for " << timeToWait.count() << "msec" << std::endl; // after collecting announcements for a defined time, we set the announcement callback. As a result, the announce callback is being called for all current announcements. try { receiver.start_for(timeToWait); } catch(hbm::exception::exception& e) { std::cerr << "Error starting the receiver: " << e.what() << std::endl; return 1; } receiver.setAnnounceCb(std::bind(&announceCb, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, receivingInterfaceFilter)); return 0; }
bool shouldCloseLedger ( bool anyTransactions, int previousProposers, int proposersClosed, int proposersValidated, std::chrono::milliseconds previousTime, std::chrono::milliseconds currentTime, // Time since last ledger's close time std::chrono::milliseconds openTime, // Time waiting to close this ledger std::chrono::seconds idleInterval, beast::Journal j) { using namespace std::chrono_literals; if ((previousTime < -1s) || (previousTime > 10min) || (currentTime > 10min)) { // These are unexpected cases, we just close the ledger JLOG (j.warn()) << "shouldCloseLedger Trans=" << (anyTransactions ? "yes" : "no") << " Prop: " << previousProposers << "/" << proposersClosed << " Secs: " << currentTime.count() << " (last: " << previousTime.count() << ")"; return true; } if ((proposersClosed + proposersValidated) > (previousProposers / 2)) { // If more than half of the network has closed, we close JLOG (j.trace()) << "Others have closed"; return true; } if (!anyTransactions) { // Only close at the end of the idle interval return currentTime >= idleInterval; // normal idle } // Preserve minimum ledger open time if (openTime < LEDGER_MIN_CLOSE) { JLOG (j.debug()) << "Must wait minimum time before closing"; return false; } // Don't let this ledger close more than twice as fast as the previous // ledger reached consensus so that slower validators can slow down // the network if (openTime < (previousTime / 2)) { JLOG (j.debug()) << "Ledger has not been open long enough"; return false; } // Close the ledger return true; }
void Connection::setReceiveTimeout(std::chrono::milliseconds timeout) { timeval tv; tv.tv_sec = timeout.count() / 1000; tv.tv_usec = (timeout.count() % 1000) * 1000; if (-1 == setsockopt(socket_, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv))) { close(); throw std::runtime_error("Setting receive timeout on socket failed."); } }
void ProxyDestinationMap::setResetTimer(std::chrono::milliseconds interval) { assert(interval.count() > 0); inactivityTimeout_ = static_cast<uint32_t>(interval.count()); resetTimer_ = folly::AsyncTimeout::make(proxy_->eventBase(), [this]() noexcept { resetAllInactive(); scheduleTimer(false /* initialAttempt */); }); scheduleTimer(true /* initialAttempt */); }
void foo() { std::chrono::milliseconds const timeout(400); for (int i = 1; i <= 10; ++i) { std::this_thread::sleep_for(timeout); std::lock_guard<std::mutex> const guard(mutex); std::cout << i << timeout.count() << " ms" << std::endl; } }
bool socket::wait_for(const std::chrono::milliseconds& timeout) const { auto fds = net::fd_set{}; FD_ZERO(&fds); FD_SET(m_fd, &fds); net::timeval tv{ static_cast<decltype(tv.tv_sec)>(timeout.count() / 1000), static_cast<decltype(tv.tv_usec)>(timeout.count() % 1000 * 1000) }; const auto result = net::select(m_fd+1, &fds, nullptr, nullptr, &tv); return result > 0; }
ConsensusState checkConsensus ( int previousProposers, int currentProposers, int currentAgree, int currentFinished, std::chrono::milliseconds previousAgreeTime, std::chrono::milliseconds currentAgreeTime, bool proposing, beast::Journal j) { JLOG (j.trace()) << "checkConsensus: prop=" << currentProposers << "/" << previousProposers << " agree=" << currentAgree << " validated=" << currentFinished << " time=" << currentAgreeTime.count() << "/" << previousAgreeTime.count(); if (currentAgreeTime <= LEDGER_MIN_CONSENSUS) return ConsensusState::No; if (currentProposers < (previousProposers * 3 / 4)) { // Less than 3/4 of the last ledger's proposers are present; don't // rush: we may need more time. if (currentAgreeTime < (previousAgreeTime + LEDGER_MIN_CONSENSUS)) { JLOG (j.trace()) << "too fast, not enough proposers"; return ConsensusState::No; } } // Have we, together with the nodes on our UNL list, reached the threshold // to declare consensus? if (checkConsensusReached (currentAgree, currentProposers, proposing)) { JLOG (j.debug()) << "normal consensus"; return ConsensusState::Yes; } // Have sufficient nodes on our UNL list moved on and reached the threshold // to declare consensus? if (checkConsensusReached (currentFinished, currentProposers, false)) { JLOG (j.warn()) << "We see no consensus, but 80% of nodes have moved on"; return ConsensusState::MovedOn; } // no consensus yet JLOG (j.trace()) << "no consensus"; return ConsensusState::No; }
void PIDController::setSampleTime(const std::chrono::milliseconds newSampleTime) { if (newSampleTime.count() <= 0) { return; } auto ratio = (float)newSampleTime.count() / mSampleTime.count(); mKi *= ratio; mKd /= ratio; mSampleTime = newSampleTime; }
std::string StringUtils::formatFPS(std::chrono::milliseconds delta, unsigned int precision) { std::string formatStr; long long deltaValue = delta.count(); if (deltaValue != 0.0) formatStr.append(std::to_string(1000.0 / delta.count())); else formatStr.append("0.0"); if (formatStr.size() > precision) formatStr = formatStr.substr(0, precision); return formatStr; }
void ConnectionManager::initiateGracefulShutdown( std::chrono::milliseconds idleGrace) { if (idleGrace.count() > 0) { idleLoopCallback_.scheduleTimeout(idleGrace); VLOG(3) << "Scheduling idle grace period of " << idleGrace.count() << "ms"; } else { action_ = ShutdownAction::DRAIN2; VLOG(3) << "proceeding directly to closing idle connections"; } drainAllConnections(); }
void Player::updateY(const std::chrono::milliseconds elapsed_time, const Map& map, ParticleTools& particle_tools) { // Update velocity const units::Acceleration gravity = is_jump_active_ && velocity_.y < 0 ? kJumpGravity : kGravity; velocity_.y = std::min(velocity_.y + gravity * elapsed_time.count(), kMaxSpeedY); // Calculate delta const units::Game delta = velocity_.y * elapsed_time.count(); if (delta > 0.0) { // Check collision in the direction of delta CollisionInfo info = getWallCollisionInfo(map, bottomCollision(delta)); // React to collision if (info.collided) { pos_.y = units::tileToGame(info.row) - kCollisionYBottom; velocity_.y = 0.0; is_on_ground_ = true; } else { pos_.y += delta; is_on_ground_ = false; } // Check collision in the direction opposite to delta info = getWallCollisionInfo(map, topCollision(0)); if (info.collided) { pos_.y = units::tileToGame(info.row) + kCollisionYHeight; createHeadBumpParticle(particle_tools); } } else { // Check collision in the direction of delta CollisionInfo info = getWallCollisionInfo(map, topCollision(delta)); // React to collision if (info.collided) { pos_.y = units::tileToGame(info.row) + kCollisionYHeight; createHeadBumpParticle(particle_tools); velocity_.y = 0.0; } else { pos_.y += delta; is_on_ground_ = false; } // Check collision in the direction opposite to delta info = getWallCollisionInfo(map, bottomCollision(0)); if (info.collided) { pos_.y = units::tileToGame(info.row) - kCollisionYBottom; is_on_ground_ = true; } } }
long SocketAdapterTls::nonblock_send_all(const void *buf, const size_t length, const std::chrono::milliseconds &timeout) const { size_t record_size = ::gnutls_record_get_max_size(this->session); if (0 == record_size) { return -1; } size_t total = 0; while (total < length) { ::gnutls_record_set_timeout(this->session, static_cast<unsigned int>(timeout.count() ) ); if (record_size > length - total) { record_size = length - total; } const long send_size = ::gnutls_record_send(this->session, reinterpret_cast<const uint8_t *>(buf) + total, record_size); if (send_size < 0) { return send_size; } total += send_size; } return static_cast<long>(total); }
bool cGhast::Attack(std::chrono::milliseconds a_Dt) { m_AttackInterval += (static_cast<float>(a_Dt.count()) / 1000) * m_AttackRate; if ((m_Target != nullptr) && (m_AttackInterval > 3.0)) { // Setting this higher gives us more wiggle room for attackrate Vector3d Speed = GetLookVector() * 20; Speed.y = Speed.y + 1; cGhastFireballEntity * GhastBall = new cGhastFireballEntity(this, GetPosX(), GetPosY() + 1, GetPosZ(), Speed); if (GhastBall == nullptr) { return false; } if (!GhastBall->Initialize(*m_World)) { delete GhastBall; GhastBall = nullptr; return false; } m_World->BroadcastSpawnEntity(*GhastBall); m_AttackInterval = 0.0; return true; } return false; }
void write_concern::majority(std::chrono::milliseconds timeout) { const auto count = timeout.count(); if ((count < 0) || (count >= std::numeric_limits<std::int32_t>::max())) throw logic_error{error_code::k_invalid_parameter}; libmongoc::write_concern_set_wmajority(_impl->write_concern_t, static_cast<std::int32_t>(count)); }
void cLuaState::Push(std::chrono::milliseconds a_Value) { ASSERT(IsValid()); tolua_pushnumber(m_LuaState, static_cast<lua_Number>(a_Value.count())); m_NumCurrentFunctionArgs += 1; }
void Timer::sleep(std::chrono::milliseconds duration) { assert(dispatcher != nullptr); assert(context == nullptr); if (stopped) { throw InterruptedException(); } Dispatcher::OperationContext timerContext; timerContext.context = dispatcher->getCurrentContext(); timerContext.interrupted = false; timer = dispatcher->getTimer(); struct kevent event; EV_SET(&event, timer, EVFILT_TIMER, EV_ADD | EV_ENABLE | EV_ONESHOT, 0, duration.count(), &timerContext); if (kevent(dispatcher->getKqueue(), &event, 1, NULL, 0, NULL) == -1) { throw std::runtime_error("Timer::stop, kevent() failed, errno=" + std::to_string(errno)); } context = &timerContext; dispatcher->dispatch(); assert(dispatcher != nullptr); assert(timerContext.context == dispatcher->getCurrentContext()); assert(context == &timerContext); context = nullptr; timerContext.context = nullptr; dispatcher->pushTimer(timer); if (timerContext.interrupted) { throw InterruptedException(); } }
std::unique_ptr<MessageDecoder> Connection::sendSyncMessageFromSecondaryThread(uint64_t syncRequestID, std::unique_ptr<MessageEncoder> encoder, std::chrono::milliseconds timeout) { ASSERT(RunLoop::current() != m_clientRunLoop); if (!isValid()) return nullptr; SecondaryThreadPendingSyncReply pendingReply; // Push the pending sync reply information on our stack. { MutexLocker locker(m_syncReplyStateMutex); if (!m_shouldWaitForSyncReplies) return nullptr; ASSERT(!m_secondaryThreadPendingSyncReplyMap.contains(syncRequestID)); m_secondaryThreadPendingSyncReplyMap.add(syncRequestID, &pendingReply); } sendMessage(std::move(encoder), 0); pendingReply.semaphore.wait(currentTime() + (timeout.count() / 1000.0)); // Finally, pop the pending sync reply information. { MutexLocker locker(m_syncReplyStateMutex); ASSERT(m_secondaryThreadPendingSyncReplyMap.contains(syncRequestID)); m_secondaryThreadPendingSyncReplyMap.remove(syncRequestID); } return std::move(pendingReply.replyDecoder); }
void PIT::start_timer(Timer t, std::chrono::milliseconds in_msecs){ if (in_msecs < 1ms) panic("Can't wait less than 1 ms. "); if (current_mode_ != RATE_GEN) set_mode(RATE_GEN); if (current_freq_divider_ != millisec_interval) set_freq_divider(millisec_interval); auto cycles_pr_millisec = KHz(CPUFrequency()); debug("<PIT start_timer> CPU KHz: %f Cycles to wait: %f \n",cycles_pr_millisec.count(), cycles_pr_millisec.count() * in_msecs); auto ticks = in_msecs / KHz(current_frequency()).count(); debug("<PIT start_timer> PIT KHz: %f * %i = %f ms. \n", KHz(current_frequency()).count(), (uint32_t)ticks.count(), ((uint32_t)ticks.count() * KHz(current_frequency()).count())); t.setStart(OS::cycles_since_boot()); t.setEnd(t.start() + uint64_t(cycles_pr_millisec.count() * in_msecs.count())); auto key = millisec_counter + ticks.count(); // We could emplace, but the timer exists allready, and might be a reused one timers_.insert(std::make_pair(key, t)); debug("<PIT start_timer> Key: %i id: %i, t.cond()(): %s There are %i timers. \n", (uint32_t)key, t.id(), t.cond()() ? "true" : "false", timers_.size()); }
void Timer::sleep(std::chrono::milliseconds duration) { assert(dispatcher != nullptr); assert(context == nullptr); if (stopped) { throw InterruptedException(); } TimerContext context2; context2.dispatcher = dispatcher; context2.context = dispatcher->getCurrentContext(); context2.interrupted = false; struct kevent event; EV_SET(&event, timer, EVFILT_TIMER, EV_ADD | EV_ENABLE | EV_ONESHOT, 0, duration.count(), &context2); if (kevent(dispatcher->getKqueue(), &event, 1, NULL, 0, NULL) == -1) { std::cerr << "kevent() failed, errno=" << errno << '.' << std::endl; throw std::runtime_error("Timer::sleep"); } context = &context2; dispatcher->yield(); assert(dispatcher != nullptr); assert(context2.context == dispatcher->getCurrentContext()); assert(context == &context2); context = nullptr; context2.context = nullptr; if (context2.interrupted) { throw InterruptedException(); } }
void cBlaze::Attack(std::chrono::milliseconds a_Dt) { m_AttackInterval += (static_cast<float>(a_Dt.count()) / 1000) * m_AttackRate; if ((m_Target != nullptr) && (m_AttackInterval > 3.0)) { // Setting this higher gives us more wiggle room for attackrate Vector3d Speed = GetLookVector() * 20; Speed.y = Speed.y + 1; cFireChargeEntity * FireCharge = new cFireChargeEntity(this, GetPosX(), GetPosY() + 1, GetPosZ(), Speed); if (FireCharge == nullptr) { return; } if (!FireCharge->Initialize(*m_World)) { delete FireCharge; FireCharge = nullptr; return; } m_World->BroadcastSpawnEntity(*FireCharge); m_AttackInterval = 0.0; // ToDo: Shoot 3 fireballs instead of 1. } }
void setSyncInterval(uint16_t deviceID, std::chrono::milliseconds syncInterval) { sendSDO(deviceID, "ip_time_units", static_cast<uint32_t>( syncInterval.count() )); sendSDO(deviceID, "ip_time_index", "milliseconds"); sendSDO(deviceID, "sync_timeout_factor", 0); // 0 = disable sync timeout }
bool BaseThriftServer::getTaskExpireTimeForRequest( std::chrono::milliseconds clientQueueTimeoutMs, std::chrono::milliseconds clientTimeoutMs, std::chrono::milliseconds& queueTimeout, std::chrono::milliseconds& taskTimeout) const { taskTimeout = getTaskExpireTime(); queueTimeout = clientQueueTimeoutMs; if (queueTimeout == std::chrono::milliseconds(0)) { queueTimeout = getQueueTimeout(); } if (taskTimeout != std::chrono::milliseconds(0) && getUseClientTimeout()) { // we add 10% to the client timeout so that the request is much more likely // to timeout on the client side than to read the timeout from the server // as a TApplicationException (which can be confusing) taskTimeout = std::chrono::milliseconds((uint32_t)(clientTimeoutMs.count() * 1.1)); } // Queue timeout shouldn't be greater than task timeout if (taskTimeout < queueTimeout && taskTimeout != std::chrono::milliseconds(0)) { queueTimeout = taskTimeout; } return queueTimeout != taskTimeout; }
bool EventBase::scheduleTimeout(AsyncTimeout* obj, std::chrono::milliseconds timeout) { assert(isInEventBaseThread()); // Set up the timeval and add the event struct timeval tv; tv.tv_sec = timeout.count() / 1000LL; tv.tv_usec = (timeout.count() % 1000LL) * 1000LL; struct event* ev = obj->getEvent(); if (event_add(ev, &tv) < 0) { LOG(ERROR) << "EventBase: failed to schedule timeout: " << strerror(errno); return false; } return true; }
zrpc::tBinaryPackage zrpc::CSocket::Handshake(const tBinaryPackage& package, const std::chrono::milliseconds total_timeout/* = std::chrono::milliseconds::max()*/, const std::chrono::milliseconds retry_timeout/* = std::chrono::milliseconds(100)*/) { using namespace std::chrono; auto start = system_clock::now(); if(m_is_sync) { while(!Send(package)) { if(duration_cast<milliseconds>(system_clock::now() - start) >= total_timeout) timeout_error("Failed to send the package on time"); boost::chrono::milliseconds boost_timeout(retry_timeout.count()); boost::this_thread::sleep_for(boost_timeout); } }else Send(package); auto send_finish = system_clock::now(); if(duration_cast<milliseconds>(send_finish - start) >= total_timeout) timeout_error("Failed to send the package on time"); tBinaryPackage answer_package; auto recv_timeout = total_timeout - duration_cast<milliseconds>(send_finish - start); if(!Recv(answer_package, recv_timeout)) timeout_error("Failed to recv the package on time"); return answer_package; }
void cFireSimulator::SimulateChunk(std::chrono::milliseconds a_Dt, int a_ChunkX, int a_ChunkZ, cChunk * a_Chunk) { cCoordWithIntList & Data = a_Chunk->GetFireSimulatorData(); int NumMSecs = static_cast<int>(a_Dt.count()); for (cCoordWithIntList::iterator itr = Data.begin(); itr != Data.end();) { int x = itr->x; int y = itr->y; int z = itr->z; BLOCKTYPE BlockType = a_Chunk->GetBlock(x, y, z); if (!IsAllowedBlock(BlockType)) { // The block is no longer eligible (not a fire block anymore; a player probably placed a block over the fire) FLOG("FS: Removing block {%d, %d, %d}", itr->x + a_ChunkX * cChunkDef::Width, itr->y, itr->z + a_ChunkZ * cChunkDef::Width ); itr = Data.erase(itr); continue; } // Try to spread the fire: TrySpreadFire(a_Chunk, itr->x, itr->y, itr->z); itr->Data -= NumMSecs; if (itr->Data >= 0) { // Not yet, wait for it longer ++itr; continue; } // Burn out the fire one step by increasing the meta: /* FLOG("FS: Fire at {%d, %d, %d} is stepping", itr->x + a_ChunkX * cChunkDef::Width, itr->y, itr->z + a_ChunkZ * cChunkDef::Width ); */ NIBBLETYPE BlockMeta = a_Chunk->GetMeta(x, y, z); if (BlockMeta == 0x0f) { // The fire burnt out completely FLOG("FS: Fire at {%d, %d, %d} burnt out, removing the fire block", itr->x + a_ChunkX * cChunkDef::Width, itr->y, itr->z + a_ChunkZ * cChunkDef::Width ); a_Chunk->SetBlock(itr->x, itr->y, itr->z, E_BLOCK_AIR, 0); RemoveFuelNeighbors(a_Chunk, itr->x, itr->y, itr->z); itr = Data.erase(itr); continue; } if ((itr->y > 0) && (!DoesBurnForever(a_Chunk->GetBlock(itr->x, itr->y - 1, itr->z)))) { a_Chunk->SetMeta(x, y, z, BlockMeta + 1); } itr->Data = GetBurnStepTime(a_Chunk, itr->x, itr->y, itr->z); // TODO: Add some randomness into this } // for itr - Data[] }