Example #1
0
void GMainLoopSource::scheduleAfterDelay(const char* name, std::function<void ()> function, std::chrono::milliseconds delay, int priority, std::function<void ()> destroyFunction, GMainContext* context)
{
    cancel();

    ASSERT(!m_context.source);
    m_context = {
        adoptGRef(g_timeout_source_new(delay.count())),
        nullptr, // cancellable
        nullptr, // socketCancellable
        WTF::move(function),
        nullptr, // boolCallback
        nullptr, // socketCallback
        WTF::move(destroyFunction)
    };
    scheduleTimeoutSource(name, reinterpret_cast<GSourceFunc>(voidSourceCallback), priority, context);
}
Example #2
0
std::unique_ptr<MessageDecoder> Connection::waitForSyncReply(uint64_t syncRequestID, std::chrono::milliseconds timeout, unsigned syncSendFlags)
{
    double absoluteTime = currentTime() + (timeout.count() / 1000.0);

    bool timedOut = false;
    while (!timedOut) {
        // First, check if we have any messages that we need to process.
        m_syncMessageState->dispatchMessages(0);
        
        {
            MutexLocker locker(m_syncReplyStateMutex);

            // Second, check if there is a sync reply at the top of the stack.
            ASSERT(!m_pendingSyncReplies.isEmpty());
            
            PendingSyncReply& pendingSyncReply = m_pendingSyncReplies.last();
            ASSERT_UNUSED(syncRequestID, pendingSyncReply.syncRequestID == syncRequestID);
            
            // We found the sync reply, or the connection was closed.
            if (pendingSyncReply.didReceiveReply || !m_shouldWaitForSyncReplies)
                return std::move(pendingSyncReply.replyDecoder);
        }

        // Processing a sync message could cause the connection to be invalidated.
        // (If the handler ends up calling Connection::invalidate).
        // If that happens, we need to stop waiting, or we'll hang since we won't get
        // any more incoming messages.
        if (!isValid())
            return nullptr;

        // We didn't find a sync reply yet, keep waiting.
        // This allows the WebProcess to still serve clients while waiting for the message to return.
        // Notably, it can continue to process accessibility requests, which are on the main thread.
        if (syncSendFlags & SpinRunLoopWhileWaitingForReply) {
#if PLATFORM(MAC)
            // FIXME: Although we run forever, any events incoming will cause us to drop out and exit out. This however doesn't
            // account for a timeout value passed in. Timeout is always NoTimeout in these cases, but that could change.
            RunLoop::current()->runForDuration(1e10);
            timedOut = currentTime() >= absoluteTime;
#endif
        } else
            timedOut = !m_syncMessageState->wait(absoluteTime);
        
    }

    return nullptr;
}
Example #3
0
void Poller::poll(std::chrono::milliseconds const& timeout)
{
    size_t begin_seq = event_buffer_.published_sequence() + 1;
    epoll_event* free_event_begin = &event_buffer_.raw_event(begin_seq);
    size_t next_seq;
    while ((next_seq = event_buffer_.max_usable_block_sequence()) < begin_seq)
        std::this_thread::yield(); // TODO wait strategy

    event_buffer_.claim(next_seq);
    int event_num = ::epoll_wait(raw_handle_, free_event_begin, next_seq - begin_seq + 1,
                                 timeout.count());
    if (event_num > 0) {
        event_buffer_.publish(begin_seq + event_num - 1);
    } else if (event_num == -1) { // TODO EINTR
        throw std::system_error(util::errc(), "Poller::poll");
    }
}
Example #4
0
int
Request_waiter::Wait_and_process_impl(const Container_list &containers,
                                   std::chrono::milliseconds timeout,
                                   int requests_limit, Predicate ext_predicate)
{
    std::unique_lock<std::mutex> lock(mutex);
    int total_processed = 0;

    /* Predicate for checking and processing requests if any. */
    auto predicate = [&]()
    {
        int num_processed = 0;
        bool is_disabled = false;
        int cur_processed;
        /* Do in rounds for a case when processing generates some requests for the
         * same containers.
         */
        do {
            cur_processed = 0;
            for (auto &container: containers) {
                if (!container->Is_enabled()) {
                    is_disabled = true;
                } else {
                    cur_processed += container->Process_requests(lock, requests_limit);
                    if (requests_limit && num_processed + cur_processed >= requests_limit) {
                        break;
                    }
                }
            }
            num_processed += cur_processed;
        } while (cur_processed && (!requests_limit || num_processed < requests_limit));
        total_processed += num_processed;
        return ext_predicate ? ext_predicate() : (num_processed || is_disabled);
    };

    if (predicate()) {
        return total_processed;
    }
    /* No requests in the queues, so the lock was not released, safe to wait. */
    if (timeout.count()) {
        cond_var.wait_for(lock, timeout, predicate);
    } else {
        cond_var.wait(lock, predicate);
    }
    return total_processed;
}
Example #5
0
//ddd:hh:mm:ss.ccc
std::string time_format(const std::chrono::milliseconds duration)
{
	char time[17] = "            .   "; //ddd:hh:mm:ss.ccc
	int char_0 = static_cast<int>('0');

	typedef std::chrono::duration<int, std::ratio<24*3600> > days;
	long long c = duration.count() % 1000;
	long long s = std::chrono::duration_cast<std::chrono::seconds>(duration).count() % 60;
	int m = std::chrono::duration_cast<std::chrono::minutes>(duration).count() % 60;
	int h = std::chrono::duration_cast<std::chrono::hours>(duration).count() % 24;
	int d = std::chrono::duration_cast<days>(duration).count();

	if (d/100)
		time[0] = char_0 + d/100;
	if (d/10)
		time[1] = char_0 + (d/10)%10;
	if (d)
	{
		time[2] = char_0 + d%10;
		time[3] = ':';
	}
	if (d || h/10)
		time[4] = char_0 + h/10;
	if (d || h)
	{
		time[5] = char_0 + h%10;
		time[6] = ':';
	}
	if (d || h || m/10)
		time[7] = char_0 + m/10;
	if (d || h || m)
	{
		time[8] = char_0 + m%10;
		time[9] = ':';
	}
	if (d || h || m || s/10)
		time[10] = char_0 + s/10;

	time[11] = char_0 + s%10;
	time[13] = char_0 + c/100;
	time[14] = char_0 + (c/10)%10;
	time[15] = char_0 + c%10;

	return std::string(time);
}
Example #6
0
BOOL CMultithreadDlg::Cls_OnInitDialog(HWND hwnd, HWND hwndFocus, LPARAM lParam) 
{
	hList = GetDlgItem(hwnd, IDC_LIST1);
	SendMessage(hList, LB_ADDSTRING, 0, LPARAM(std::to_wstring(FindTime().count() * 1.0 / 1000).c_str()));
	//InitializeCriticalSection(&CriticalSelection);
	HANDLE handle1 = CreateThread(NULL, 0, Thread1, (LPVOID)0, 0, NULL);
	HANDLE handle2 =  CreateThread(NULL, 0, Thread1, (LPVOID)1, 0, NULL);	
	HANDLE handle3 = CreateThread(NULL, 0, Thread1, (LPVOID)2, 0, NULL);
	WaitForSingleObject(handle1, INFINITE);
	WaitForSingleObject(handle2, INFINITE);
	WaitForSingleObject(handle3, INFINITE);
	//DeleteCriticalSection(&CriticalSelection);
	SendMessage(hList, LB_ADDSTRING, 0, LPARAM(std::to_wstring(times.count() * 1.0 / 1000).c_str()));
	ofs0.close();
	ofs1.close();
	ofs.close();
	return TRUE;
}
Example #7
0
std::pair<AlgorithmIdentifier, std::vector<uint8_t>>
pbes2_encrypt_msec(const secure_vector<uint8_t>& key_bits,
                   const std::string& passphrase,
                   std::chrono::milliseconds msec,
                   size_t* out_iterations_if_nonnull,
                   const std::string& cipher,
                   const std::string& digest,
                   RandomNumberGenerator& rng)
   {
   size_t msec_in_iterations_out = static_cast<size_t>(msec.count());

   auto ret = pbes2_encrypt_shared(key_bits, passphrase, &msec_in_iterations_out, 0, cipher, digest, rng);

   if(out_iterations_if_nonnull)
      *out_iterations_if_nonnull = msec_in_iterations_out;

   return ret;
   }
Example #8
0
void CScreen::printResult(const int number, const int depth, const int selectivity, const uint64_t P, const uint64_t O, const int score, const std::chrono::milliseconds duration, const uint64_t NodeCounter, const std::string& PV)
{
	positionCounter.fetch_add(1, std::memory_order_relaxed);

	if (verbose == 1)
	{
		if (!flag.test_and_set(std::memory_order_acquire))
		{
			if (std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - lastPrint).count() > 500)
			{
				if (positions)
				{
					std::unique_lock<std::mutex> lock(mtx);
					std::cout << "\r" << ThousandsSeparator(positionCounter.load(std::memory_order_acquire)) << " positions solved.   " << positionCounter.load(std::memory_order_acquire) * 100 / positions << "%    " << ETA();
					fflush(stdout);
				}
				else
				{
					std::unique_lock<std::mutex> lock(mtx);
					std::cout << "\r" << ThousandsSeparator(positionCounter.load(std::memory_order_acquire)) << " positions solved in             " << time_format(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - startTime));
					fflush(stdout);
				}
				lastPrint = std::chrono::high_resolution_clock::now();
			}
			flag.clear(std::memory_order_release);
		}
	}
	else if (verbose == 2)
	{
		std::unique_lock<std::mutex> lock(mtx);
		printf("%*d|%6s| %+2.2d |%16s|%*s|%*s| %s\n", width_number, number, DepthSelectivity(depth, selectivity, P, O).c_str(), score,
			time_format(duration).c_str(), width_nodes, ThousandsSeparator(NodeCounter).c_str(),
			width_nps, (duration.count() == 0 ? nullptr : ThousandsSeparator(NodeCounter * 1000ULL / duration.count()).c_str()),
			PV.c_str());
	}
	else if (verbose == 3)
	{
		std::string L1, L2;
		GetLines(L1, L2);
		std::unique_lock<std::mutex> lock(mtx);
		std::cout << L2 << std::endl;
	}
}
Example #9
0
std::shared_ptr<TcpSocket> TcpSocket::Accept(const std::chrono::milliseconds& timeout)
{
    std::unique_ptr<timeval> tv;
    if (timeout.count() != 0)
    {
        std::chrono::seconds timeoutSeconds = std::chrono::duration_cast<std::chrono::seconds>(timeout);
        std::chrono::milliseconds timeoutRemainder = timeout - std::chrono::duration_cast<std::chrono::milliseconds>(timeoutSeconds);
        std::chrono::microseconds timeoutMicroseconds = std::chrono::duration_cast<std::chrono::microseconds>(timeoutRemainder);
        
        tv.reset(new timeval());
        tv->tv_sec = (decltype(tv->tv_sec))timeoutSeconds.count();
        tv->tv_usec = (decltype(tv->tv_usec))timeoutMicroseconds.count();
    }

    // Select the server socket for checking incoming connection.
    fd_set readfds;
    FD_ZERO(&readfds);
    FD_SET(mSocket, &readfds);
    
    // Wait until timeout for incoming connection, tv = NULL for blocking operation.
    int32_t result = select((int32_t)mSocket + 1, &readfds, nullptr, nullptr, tv.get());
    if (result == SOCKET_ERROR)
    {
        // select error
        int32_t error = GetSocketError();
        THROW(SocketException, error);
    }
    else if (result > 0)
    {
        // Accept a client socket
        SOCKET socket = accept(mSocket, nullptr, nullptr);
        if (socket == INVALID_SOCKET)
        {
            return nullptr;
        }
        
        std::shared_ptr<TcpSocket> clientSocket = std::make_shared<TcpSocket>(socket);
        clientSocket->SetNonblocking(true);
        return clientSocket;
    }

    return nullptr;
}
void AsyncMcClientImpl::updateWriteTimeout(std::chrono::milliseconds timeout) {
  if (!timeout.count()) {
    return;
  }
  auto selfWeak = selfPtr_;
  eventBase_.runInEventBaseThread([selfWeak, timeout]() {
      if (auto self = selfWeak.lock()) {
        if (!self->connectionOptions_.writeTimeout.count() ||
            self->connectionOptions_.writeTimeout > timeout) {
          self->connectionOptions_.writeTimeout = timeout;
        }

        if (self->socket_) {
          self->socket_->setSendTimeout(
            self->connectionOptions_.writeTimeout.count());
        }
      }
    });
}
Example #11
0
/* Ensure that we're synchronized with the state of the
 * filesystem at the current time.
 * We do this by touching a cookie file and waiting to
 * observe it via inotify.  When we see it we know that
 * we've seen everything up to the point in time at which
 * we're asking questions.
 * Returns true if we observe the change within the requested
 * time, false otherwise.
 * Must be called with the root UNLOCKED.  This function
 * will acquire and release the root lock.
 */
bool watchman_root::syncToNow(std::chrono::milliseconds timeout) {
  w_perf_t sample("sync_to_now");

  auto res = cookies.syncToNow(timeout);

  // We want to know about all timeouts
  if (!res) {
    sample.force_log();
  }
  if (sample.finish()) {
    sample.add_root_meta(shared_from_this());
    sample.add_meta(
        "sync_to_now",
        json_object({{"success", json_boolean(res)},
                     {"timeoutms", json_integer(timeout.count())}}));
    sample.log();
  }

  return res;
}
Example #12
0
PendingCollection::LockedPtr PendingCollection::lockAndWait(
    std::chrono::milliseconds timeoutms,
    bool& pinged) {
  auto lock = wlock();

  if (lock->checkAndResetPinged()) {
    pinged = true;
    return lock;
  }

  if (timeoutms.count() == -1) {
    cond_.wait(lock.getUniqueLock());
  } else {
    cond_.wait_for(lock.getUniqueLock(), timeoutms);
  }

  pinged = lock->checkAndResetPinged();

  return lock;
}
Example #13
0
void
runloop::schedule( event e, std::chrono::milliseconds msec, event_f func )
{
	auto event	= static_cast< ppapi_timer_event* >( e );
	auto module	= static_cast< pp::Module* >( nullptr );
	auto core	= static_cast< pp::Core* >( nullptr );

	nrequire( event, exit );
	module = pp::Module::Get();
	nrequire( module, exit );
	core = module->core();
	nrequire( core, exit );
	
	event->m_active = true;
	
	core->CallOnMainThread( msec.count(), m_factory.NewCallback( &runloop::on_timer, e, func ), 0 );

exit:

	return;
}
    /// Used to report the time taken by a timed function, called by
    /// the TIME_FUNCTION macro
    void
    ReportTimedFunction(const char* fnName,
                        const std::chrono::milliseconds duration)
    {
        switch (mode_)
        {
        case Mode::None:
            break;

        case Mode::StdOut:
        {
            LOG("Function %s, took %s ms", fnName,
                std::to_string(duration.count()).c_str());

        } break;

        case Mode::JSONStdOut:
        {
            stream_->EnqueueFunctionTimeData(fnName, duration);
        }
        }
    }
Example #15
0
HttpRequest::Impl::Impl(std::chrono::milliseconds timeout_ms, ProgressCallback callback)
    : m_callback(callback)
{
  {
    std::lock_guard<std::mutex> lk(s_curl_was_inited_mutex);
    if (!s_curl_was_inited)
    {
      curl_global_init(CURL_GLOBAL_DEFAULT);
      s_curl_was_inited = true;
    }
  }

  m_curl.reset(curl_easy_init());
  if (!m_curl)
    return;

  curl_easy_setopt(m_curl.get(), CURLOPT_NOPROGRESS, m_callback == nullptr);

  if (m_callback)
  {
    curl_easy_setopt(m_curl.get(), CURLOPT_PROGRESSDATA, this);
    curl_easy_setopt(m_curl.get(), CURLOPT_PROGRESSFUNCTION, CurlProgressCallback);
  }

  // libcurl may not have been built with async DNS support, so we disable
  // signal handlers to avoid a possible and likely crash if a resolve times out.
  curl_easy_setopt(m_curl.get(), CURLOPT_NOSIGNAL, true);
  curl_easy_setopt(m_curl.get(), CURLOPT_CONNECTTIMEOUT_MS, static_cast<long>(timeout_ms.count()));
  // Sadly CURLOPT_LOW_SPEED_TIME doesn't have a millisecond variant so we have to use seconds
  curl_easy_setopt(
      m_curl.get(), CURLOPT_LOW_SPEED_TIME,
      static_cast<long>(std::chrono::duration_cast<std::chrono::seconds>(timeout_ms).count()));
  curl_easy_setopt(m_curl.get(), CURLOPT_LOW_SPEED_LIMIT, 1);
#ifdef _WIN32
  // ALPN support is enabled by default but requires Windows >= 8.1.
  curl_easy_setopt(m_curl.get(), CURLOPT_SSL_ENABLE_ALPN, false);
#endif
}
Example #16
0
Text_stream_filter::Entry_handle
Text_stream_filter::Add_entry(const regex::regex &re, Match_handler handler,
                              std::chrono::milliseconds timeout,
                              size_t ctx_lines_before, size_t ctx_lines_after)
{
    Entry_handle handle = cur_handle++;
    Entry &e =
        entries.emplace(handle, Entry(handle, re, handler,
                                      ctx_lines_before,
                                      ctx_lines_after)).first->second;
    e.timeout = timeout;
    if (timeout.count()) {
        e.timer = Timer_processor::Get_instance()->Create_timer(
            timeout,
            Make_callback(&Text_stream_filter::Timeout_handler, this, &e),
            comp_ctx);
    }
    if (stream->Is_closed()) {
        /* To make sure, that stream close event is propagated to new entry. */
        Schedule_read();
    }
    return handle;
}
void Database::setBusyTimeout(std::chrono::milliseconds timeout) {
    assert(impl);

    // std::chrono::milliseconds.count() is a long and Qt will cast
    // internally to int, so we need to make sure the limits apply.
    std::string timeoutStr = mbgl::util::toString(timeout.count() & INT_MAX);

    auto db = QSqlDatabase::database(impl->connectionName);
    QString connectOptions = db.connectOptions();
    if (connectOptions.isEmpty()) {
        if (!connectOptions.isEmpty()) connectOptions.append(';');
        connectOptions.append("QSQLITE_BUSY_TIMEOUT=").append(QString::fromStdString(timeoutStr));
    }
    if (db.isOpen()) {
        db.close();
    }
    db.setConnectOptions(connectOptions);
    if (!db.open()) {
        // Assume every error when opening the data as CANTOPEN. Qt
        // always returns -1 for `nativeErrorCode()` on database errors.
        throw Exception { ResultCode::CantOpen, "Error opening the database." };
    }
}
Example #18
0
	static Float heat(std::chrono::milliseconds t, Float heatCapacity, Float heatGeneration) {
		return heatCapacity - std::exp(-t.count() / 1000.0 * heatGeneration);
	}
Example #19
0
	long SocketAdapterTls::nonblock_recv(std::vector<std::string::value_type> &buf, const std::chrono::milliseconds &timeout) const
	{
		::gnutls_record_set_timeout(this->session, static_cast<unsigned int>(timeout.count() ) );
		return ::gnutls_record_recv(this->session, buf.data(), buf.size() );
	}
void ProxyDestinationMap::setResetTimer(std::chrono::milliseconds interval) {
  assert(interval.count() > 0);
  auto delay = to<timeval_t>((unsigned int)interval.count());
  resetTimer_ = asox_add_timer(proxy_->eventBase->getLibeventBase(), delay,
                               onResetTimer, this);
}
Example #21
0
int main(int argc, char** argv) {
	namespace po = boost::program_options;
	po::options_description desc("Options");
	desc.add_options()
		("help", "Print help messages")
		("handystats-config", po::value<std::string>(),
			"Handystats configuration (in JSON format)"
		)
		("threads", po::value<uint64_t>(&threads)->default_value(threads),
			"Number of worker threads"
		)
		("step", po::value<std::vector<uint64_t>>(&steps)->multitoken()->required(),
			"Load step pairs (rate, seconds), e.g. --step 100 10 --step 200 10"
		)
		("timers", po::value<uint64_t>(&timers)->default_value(timers),
			"Number of different timers (0 for no timers)"
		)
		("counters", po::value<uint64_t>(&counters)->default_value(counters),
			"Number of different counters (0 for no counters)"
		)
		("gauges", po::value<uint64_t>(&gauges)->default_value(gauges),
			"Number of different gauges (0 for no gauges)"
		)
		("output-interval", po::value<uint64_t>()->default_value(output_interval.count()),
			"Stats output interval (in milliseconds)"
		)
	;

	po::variables_map vm;
	try {
		po::store(po::parse_command_line(argc, argv, desc), vm);
		if (vm.count("help")) {
			std::cout << desc << std::endl;
			return 0;
		}
		po::notify(vm);
	}
	catch(po::error& e) {
		std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
		std::cerr << desc << std::endl;
		return 1;
	}

	if (vm["threads"].as<uint64_t>() == 0) {
		std::cerr << "ERROR: number of threads must be greater than 0" << std::endl;
		return 1;
	}

	if (!vm["timers"].as<uint64_t>() && !vm["counters"].as<uint64_t>() && !vm["gauges"].as<uint64_t>()) {
		std::cerr << "ERROR: at least one metric type must be specified (timers, counters, gauges)" << std::endl;
		return 1;
	}

	if (vm.count("handystats-config")) {
		HANDY_CONFIG_JSON(vm["handystats-config"].as<std::string>().c_str());
	}

	output_interval = std::chrono::milliseconds(vm["output-interval"].as<uint64_t>());

	HANDY_INIT();

	std::atomic<bool> stop_flag(false);
	std::thread stats_printer(
			[&stop_flag] () {
				while (!stop_flag.load()) {
					const auto& start_time = handystats::chrono::tsc_clock::now();
					print_stats();
					const auto& end_time = handystats::chrono::tsc_clock::now();

					const auto& call_time = handystats::chrono::duration::convert_to(
							handystats::chrono::time_unit::NSEC, end_time - start_time
						);
					std::this_thread::sleep_for(output_interval - std::chrono::nanoseconds(call_time.count()));
				}
			}
		);

	std::vector<std::thread> workers(threads);
	for (size_t step_index = 0; step_index < steps.size(); step_index += 2) {
		uint64_t step_rate = steps[step_index];
		uint64_t step_time_limit = steps[step_index + 1];

		if (step_time_limit == 0) {
			continue;
		}

		rate.store(step_rate);
		end_time.store(
				handystats::chrono::duration::convert_to(handystats::chrono::time_unit::USEC,
					(
						handystats::chrono::tsc_clock::now() +
						handystats::chrono::duration(step_time_limit, handystats::chrono::time_unit::SEC)
					).time_since_epoch()
				).count()
			);

		if (step_rate == 0) {
			std::this_thread::sleep_for(std::chrono::seconds(step_time_limit));
			continue;
		}

		handystats::chrono::duration command_time_limit =
			handystats::chrono::duration::convert_to(
					handystats::chrono::time_unit::NSEC,
					handystats::chrono::duration(1, handystats::chrono::time_unit::SEC)
				) * threads / step_rate;
		handystats::chrono::duration time_limit(step_time_limit, handystats::chrono::time_unit::SEC);

		for (auto& worker : workers) {
			worker = std::thread(
					[command_time_limit, time_limit]
					() {
						handystats::benchmarks::command_executor::run_for(
							[] () {
								command();
							},
							command_time_limit,
							time_limit
						);
					}
				);
		}

		for (auto& worker : workers) {
			worker.join();
		}
	}

	stop_flag.store(true);
	stats_printer.join();

	HANDY_FINALIZE();
}
Example #22
0
float BatteryObserver::calculateEnergyConsumption(const std::chrono::milliseconds duration, const float power) const
{
    return (power * duration.count()) /
           (std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::hours(1)).count());
}
Example #23
0
	bool SocketList::recv(std::vector<Socket> &sockets, std::vector<Socket> &disconnected, std::chrono::milliseconds timeout) const
	{
		if (false == is_created() )
		{
			return false;
		}

	#ifdef WIN32
		const int count = ::WSAPoll(this->poll_events.data(), static_cast<::ULONG>(this->poll_events.size() ), static_cast<::INT>(timeout.count() ) );

		if (SOCKET_ERROR == count)
		{
			return false;
		}

		for (size_t i = 0; i < this->poll_events.size(); ++i)
		{
			const WSAPOLLFD &event = this->poll_events[i];

			if (event.revents & POLLRDNORM)
			{
				sockets.emplace_back(Socket(event.fd) );
			}
			else if (event.revents & POLLHUP)
			{
				disconnected.emplace_back(Socket(event.fd) );
			}
		}

		return false == sockets.empty() || false == disconnected.empty();
	#elif POSIX
		const int count = ::epoll_wait(this->obj_list, this->epoll_events.data(), this->epoll_events.size(), timeout.count() );

		if (count == ~0)
		{
			return false;
		}

		for (int i = 0; i < count; ++i)
		{
			const epoll_event &event = this->epoll_events[i];

			if (event.events & EPOLLIN)
			{
				sockets.emplace_back(Socket(event.data.fd) );
			}
			else if (event.events & EPOLLRDHUP)
			{
				disconnected.emplace_back(Socket(event.data.fd) );
			}
		}

		return false == sockets.empty() || false == disconnected.empty();
	#else
		#error "Undefine platform"
	#endif
	}
	GlobalObject::Timer::Timer(Callback_t callback, const std::chrono::milliseconds& interval)
	    : interval__(interval)
	{
		TITANIUM_LOG_DEBUG("GlobalObject::Timer: interval = ", interval.count(), "ms");
	}
Example #25
0
void cFallingBlock::Tick(std::chrono::milliseconds a_Dt, cChunk & a_Chunk)
{
	// GetWorld()->BroadcastTeleportEntity(*this);  // Test position
	
	int BlockX = POSX_TOINT;
	int BlockY = (int)(GetPosY() - 0.5);
	int BlockZ = POSZ_TOINT;
	
	if (BlockY < 0)
	{
		// Fallen out of this world, just continue falling until out of sight, then destroy:
		if (BlockY < VOID_BOUNDARY)
		{
			Destroy(true);
		}
		return;
	}
	
	if (BlockY >= cChunkDef::Height)
	{
		// Above the world, just wait for it to fall back down
		return;
	}
	
	BLOCKTYPE BlockBelow = a_Chunk.GetBlock(BlockX - a_Chunk.GetPosX() * cChunkDef::Width, BlockY, BlockZ - a_Chunk.GetPosZ() * cChunkDef::Width);
	NIBBLETYPE BelowMeta = a_Chunk.GetMeta(BlockX - a_Chunk.GetPosX() * cChunkDef::Width, BlockY, BlockZ - a_Chunk.GetPosZ() * cChunkDef::Width);
	if (cSandSimulator::DoesBreakFallingThrough(BlockBelow, BelowMeta))
	{
		// Fallen onto a block that breaks this into pickups (e. g. half-slab)
		// Must finish the fall with coords one below the block:
		cSandSimulator::FinishFalling(m_World, BlockX, BlockY, BlockZ, m_BlockType, m_BlockMeta);
		Destroy(true);
		return;
	}
	else if (!cSandSimulator::CanContinueFallThrough(BlockBelow))
	{
		// Fallen onto a solid block
		/*
		LOGD(
			"Sand: Checked below at {%d, %d, %d} (rel {%d, %d, %d}), it's %s, finishing the fall.",
			BlockX, BlockY, BlockZ,
			BlockX - a_Chunk.GetPosX() * cChunkDef::Width, BlockY, BlockZ - a_Chunk.GetPosZ() * cChunkDef::Width,
			ItemTypeToString(BlockBelow).c_str()
		);
		*/

		if (BlockY < cChunkDef::Height - 1)
		{
			cSandSimulator::FinishFalling(m_World, BlockX, BlockY + 1, BlockZ, m_BlockType, m_BlockMeta);
		}
		Destroy(true);
		return;
	}
	
	float MilliDt = a_Dt.count() * 0.001f;
	AddSpeedY(MilliDt * -9.8f);
	AddPosition(GetSpeed() * MilliDt);

	// If not static (one billionth precision) broadcast movement
	if ((fabs(GetSpeedX()) > std::numeric_limits<double>::epsilon()) || (fabs(GetSpeedZ()) > std::numeric_limits<double>::epsilon()))
	{
		BroadcastMovementUpdate();
	}
}
Example #26
0
 inline int poll(std::vector<zmq_pollitem_t> const& items, std::chrono::milliseconds timeout)
 {
     return poll(items.data(), items.size(), timeout.count() );
 }
Example #27
0
 inline int poll(zmq_pollitem_t const* items, size_t nitems, std::chrono::milliseconds timeout)
 {
     return poll(items, nitems, timeout.count() );
 }
Example #28
0
void write_concern::timeout(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_wtimeout(_impl->write_concern_t, static_cast<std::int32_t>(count));
}
Example #29
0
bool SysSemaphore::AcquireInMs(const std::chrono::milliseconds timeoutInMs)
{
	const bool result = AcquireInMs(static_cast<uint32_t>(timeoutInMs.count()));
	return result;
}
Example #30
0
 Window(const std::chrono::milliseconds &windowLength)
   : begin_(bolt::timeNowMilli()), end_(begin_ + windowLength.count()) {}