"why does future::select choose the future with a longer sleep period first?" Code Answer
Answers related to “why does future::select choose the future with a longer sleep period first?”
- In PHP, what is a closure and why does it use the “use” identifier?
- Why does DateTime::createFromFormat() fails and returns a boolean in my second example?
- Why does array_unique sort the values?
- Why does PHP store uploaded files in a temporary location and what is the benefit?
- Why does php function “json_encode” applied for a not-associative array with a missing first element consider...
- Why does file_get_contents() return the error “Filename cannot be empty”?
- Why does this basic imagejpeg() resizer returns a black image?
- Why does Facebook uses the img tag with PHP link [closed]
- Why does “pip install” inside Python raise a SyntaxError?
- Why does flowing off the end of a non-void function without returning a value not produce a compiler error?
- Why does modulus division (%) only work with integers?
- Why does Python code run faster in a function?
- Why does JavaScript handle the plus and minus operators between strings and numbers differently?
- Why does useState cause the component to render twice on each update?
- Why does LayoutInflater ignore the layout_width and layout_height layout parameters I've specified?
- Why does malloc initialize the values to 0 in gcc?
- Why does rand() yield the same sequence of numbers on every run?
- Why does linking lifetimes matter only with mutable references?
- Synchronously waiting for an async operation, and why does Wait() freeze the program here
- Why does C++ need the scope resolution operator?
- C programming, why does this large array declaration produce a segmentation fault?
- How do I programmatically set the connection string for Entity-Framework Code-First?
- Why does integer overflow on x86 with GCC cause an infinite loop?
- Why does Java implicitly (without cast) convert a `long` to a `float`?
- Why does overflow:hidden not work in a <td>?
- Why does '.sort()' cause the list to be 'None' in Python?
- Why does pointer decay take priority over a deduced template?
- Why does “local” sweep the return code of a command?
- Why does Sass change the format of my colors?
- Why does an onclick property set with setAttribute fail to work in IE?
- Transform Java Future into a CompletableFuture
- Why does C# limit the set of types that can be declared as const?
- How to trace the path in a Breadth-First Search?
- Why does 'continue' behave like 'break' in a Foreach-Object?
- Why does neo4j warn: “This query builds a cartesian product between disconnected patterns”?
- Order navigation properties when using Include and/or Select methods with EF 4.1 Code-First?
- How to implement depth first search for graph with a non-recursive approach
- Defining multiple Foreign Key for the Same table in Entity Framework Code First
- Why does using an Underscore character in a LIKE filter give me all the results?
- Why does haskell's bind function take a function from non-monadic to monadic
- What's the difference between a Future and a Promise?
- Composite Key with EF 4.1 Code First
- Why does Java limit the size of a method to 65535 byte?
- Why does python behave this way with variables?
- How does PostgreSQL perform ORDER BY with a b-tree index on the field?
- Why does Node.js' fs.readFile() return a buffer instead of string?
- Database in use error with Entity Framework 4 Code First
- Get the status of a std::future
- char array in structs - why does strlen() return the correct value here?
- How does plugin validation work in Maven, and why does it build my project with an invalid version?
- Why does ng-controller not work with function this this example?
- Why does rand() return the same value using srand(time(null)) in this for loop?
- StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First
- Why does .net use the UTF16 encoding for string, but uses UTF-8 as default for saving files?
- Why does generated IL code start with a Nop?
- Why does LayoutKind.Sequential work differently if a struct contains a DateTime field?
- JSF 2.2 Memory Consumption: Why does Mojarra keep the ViewScoped Beans of the last 25 Views in Memory?
- If == compares references in Java, why does it evaluate to true with these Strings?
- Why does process substitution not work in a shell script?
- Why does jQuery throw the error `fadeOut is not a function'?
- Why does this violate the type constraint?
- Why does parsing '23:00 PM' with SimpleDateFormat(“hh:mm aa”) return 11 a.m.?
- Why doesn't this jquery selector with a period work
- Why does calling sbrk(0) twice give a different value?
- Why does printf print random value with float and integer format specifier
- Why does in_array() wrongly return true with these (large numeric) strings?
- Why does Python 3 allow “00” as a literal for 0 but not allow “01” as a literal for 1?
- Why does android get the wrong ssl certificate? (two domains, one server)
- Why does Laravel's getMimeType() method identify a file as “application/octet-stream” when the file has the type...
- Android - How can I wake up the phone from a hard sleep to take a picture?
- Why does summary overestimate the R-squared with a “no-intercept” model formula
- Why does Python threading.Condition() notify() require a lock?
- Convert a Java Future to a Scala Future
- Why does std::remove not work with std::set?
- Why does C# require you to write a null check every time you fire an event?
- how to update a jLabel every time with a while loop with a delay
- Why does require in the ns form behave different from the require function
- Why does attr_accessor clobber the existing variables in this model in Ruby on Rails?
- Why Does PyGame Trail the Image?
- Why does this behave the way it does with max-width: 0?
- How would you print out the data in a binary tree, level by level, starting at the top?
- The connection string 'MyConnection' in the application's configuration file does not contain the required...
- Why does appending to TextBox.Text during a loop take up more memory with each iteration?
- Why does giving explicit type arguments to a non-generic method or constructor compile?
- Why does C# allow {} code blocks without a preceding statement?
- How do you make a program sleep in C++ on Win 32?
- Why does this const member function allow a member variable to be modified?
- How to make a Windows 10 computer go to sleep with a python script?
- Why does Android OS 8 WebVew with HTML select tag crash the app
- Why does my icon handling code throw a NullPointerException?
- What's the proper way to abandon an Azure SB Message so that it becomes visible again in the future in a way I can...
- What does the 'period' character (.) mean if used in the middle of a php string?
- Why does Java ignore the first line of a .properties file?
- Why does GCC subtract the wrong value to the stack pointer when allocating a big array with no subsequent function...
- Why does resharper say 'Catch clause with single 'throw' statement is redundant'?
- Why does React warn me against binding a component method to the object?
- Why does this url raise BadStatusLine with httplib2 and urllib2?
- Why does pool run the entire file multiple times?
- Why does code first/EF use 'nvarchar(4000)' for strings in the raw SQL command?
- Why does React discard the entire DOM subtree and recreate it from scratch?
- Why does JSLint forbid the “this” keyword?
- Why does forfiles swallow the first argument of the command?
- The context is being used in Code First mode with code that was generated from an EDMX file
- Why does insert invalidate the std::set reverse iterator
- Why does this (i = ++i % 3) generate a warning: “may be undefined”?
- Why does dynamic.ToString() return something between a string and not a string?
- Why does codeigniter store its sessiondata in a cookie?
- Why does omitting explicit 'int' type for a parameter fail to compile in gcc sometimes?
- Why does my script suddenly exit after a command?
- Why does sass fail to compile with grunt command error of “index is 2 but list is only 1 item long for `nth'”?
- Why am I getting the error: “Not a JPEG file: starts with 0x89 0x50” [closed]
- Why does Firebug say toFixed() is not a function?
- Why does an SWT Composite sometimes require a call to resize() to layout correctly?
- Why does Python's dict.keys() return a list and not a set?
- How to convert Map[A,Future[B]] to Future[Map[A,B]]?
- Pthread - What is the difference between time.h::sleep() and pthread.h::pthread_yield()?
- Why does greyscale work the way it does?
- Why does Array.prototype.reduce not have a thisObject parameter?
- Why does Kotlin allow variable declarations with the same name as a parameter inside a method?
- Why does jQuery pass the window object into their scope
- Why does Entity Framework return null List<> instead of empty ones?
- Why does binding affect the type of my map?
- Can a scheduled future cause a memory leak?
- Why does Eclipse Kepler SR1 error with : JAX-RS 2.0 requires Java 1.7 or newer
- Why does zip() drop the values of my generator?
- Why does Setting EntityState to Detached Empty a Property of type List<T>?
- Scrapy: why does my response object not have a body_as_unicode method?
- Why does JSF put String values in a Map<…, Integer>? And how to work around it?
- why does size of the struct need to be a multiple of the largest alignment of any struct member
- Why doesn't Scala's Future have a .get / get(maxDuration) method, forcing us to resort to Await.result() instead?
- How to make a thread sleep/block for nanoseconds (or at least milliseconds)?
- Dealing with a longer running process in WCF
- Why does MySQL use the wrong index?
- Why does C have keywords starting with underscore
- EF-Code first complex type with a navigational property
- Why does R store the loop variable/index/dummy in memory?
- Python: Why does equality comparing an int with a string not throw an error?
- Why does TypeScript assertion of object literal `{a}` work with interface `{a, b}` but not `{a?, b}`
- Why does Number() return wrong values with very large integers?
- Why does Java require the char variable to use single quotes?
- Why does Json.NET serialization fail with [Serializable] and a lambda inside a read-only property?
- Why does gcov report 0% coverage on a header file for a well used class?
- Why does Python change the value of an integer when there is a 0 in front of it?
- Why does trying to use Grape with Rails fail with “uninitialized constant API”?
- Map exception in completable future to a different exception type?
- How to manually update Entity framework Code first model so that it updates a database (with a new column)?
- Why does Scala evaluate the argument for a call-by-name parameter if the method is infix and right-associative?
- Why does encode delete the argument?
- Why does Spark Cassandra Connector fail with NoHostAvailableException?
- Why does Chrome read the svg circle radius from the style attribute?
- Why Does url-encoding the first slash after the domain break the url?
- Why does integer overflow cause errors with C++ iostreams?
- Why does eax contain the number of vector parameters?
- MVC3 naming a column beginning with a number
- Why does it work when I append a new element to a TUPLE?
- Why does text on the same layer overlap - even when it has an opaque background?
- Why does Thread.Sleep() freeze the Form?
- Why does mypy infer the common base type instead of the union of all contained types?
- using jsonData as a key value to send mixed data in asp: Does not update the database with the values
- Why does DbMetal Generate Table Attribute with “main”?
- MySQL table with AUTO_INCREMENT primary id does not release the number after a rollback
- Why does append overwrite the list?
- why does str_replace replaces my character with a semicolon?
- Why does make think the target is up to date?
- What is a .un~ file or or why does Vim in the Terminal make the .un~ file?
- Tying the Knot with a State monad
- Why does unique_ptr have the deleter as a type parameter while shared_ptr doesn't?
- What the purpose of OnModelCreating in EF4 Code-First?
- Using Cont to acquire values from the future and the past
- Why does serialize() have the same effect as serializeArray() when setting post data for jQuery.ajax()?
- Scala Future with filter in for comprehension
- Why does this state that WebGL is a 2D API, not a 3D API?
- Why does Clang prefer the primary template over the specialization from C++17?
- Why does v8 saves the source code of native javascript in generated binaries?
- Why does the andThen of Future not chain the result?
- Why does git submodule update fail with “fatal: remote error: upload-pack: not our ref”?
- Which is the better approach to web services - contract first or contract last?
- Why does $.getJSON() block the browser?
- Why does GetObject return an BITMAP with null bmBits?
- How to add a new code-first migration with a newly-generated database?
- Why does this code run faster with a lock?
- mapping a Stream with a function returning a Future
- How to insert a record into a table with a foreign key using Entity Framework in ASP.NET MVC
- Why does GCC optimization not work with valarrays?
- Why does mock ignore the instance/object passed to a mocked out method when it is called?
- Entity Framework Code First - One-to-Many with a join/link table
- Why does my code run slower with multiple threads than with a single thread when it is compiled for profiling (-pg)?
- Why does IE restrict the JavaScript files of local HTML pages?
- How to get the path between 2 nodes using Breadth-First Search?
- Why does setting initialFirstResponder have no effect?
- Why does returning false stop propagation with jQuery while it doesn't with POJS?
- Why does `Future#toString` returns `“List()”`?
- Why does ignoring SIGTRAP not work with asm?
- Why does C++ disallow the creation of valid pointers from a valid address and type?
- Why does Firefox use the IE box model for input elements?
- How does the tooltip control enhance all controls on the form with a new property?
- Why does Html.Label() not work with periods?
- Why does iterating over jQuery objects with .each() not give me jQuery objects?
- Scala Actors: if react never returns, why does it need to be in a loop{}, and why doesn't while(true) work?
- Why does MS Access 2007 not allow a row insert, but then allow it on the next insert attempt?
- Why does std::result_of not work with lambdas?
- How can I calculate the level of a node in a perfect binary tree from its depth-first order index?
- Why does publishing plugin project fail with RuntimeException: Repository for publishing is not specified?
- Why does calling useState's setter with the same value subsequently trigger a component update even if the old...
- How does Spring get the result from an endpoint that returns CompletableFuture object?
- Why does [NullString]::Value evaluate differently with a breakpoint?
- Why does MVC use the Modelstate over a supplied Model on a GET
- Why does Java read random amounts from a socket but not the whole message?
- Scheduling an audio file for playback in the future with AVAudioTime
- Why does EF Code First [InverseProperty] attribute fail to work when used with [ForeignKey] attribute?
- Why does my classpath only work with a colon on the end?
- Why does p:resetInput require properties of a managed bean to be set to null first after the form is submitted?
- Why does my data successfully write to a file on the iPhone simulator, but not my device?
- Why does UDP have the field "UDP Length" twice in its packet?
- Why does Perl's LWP gives me a different encoding than the original website?
- Why does PortAudio not play nicely with other audio programs or how can I get it to?
- Why does the keyboard not show when a view is popped from the navigation stack?
- Why does Safari on the iPad not display my marker on an embedded Google Maps page?
- How does one design the datasource for a UITableView in order to sort with a UISegmentedControl?
- why does ::CreateProcess(path,cmd,...) fail with error "File not found"?
- Why does GitHub need me to rebase a Merge Request when nothing has changed in the MR
- Why does map() mask the 'undefined value' error?
- Why does binding to const reference from a ternary make a copy?
- Why does Git use the SHA1 of the *compressed* objects rather than the SHA1 of the original objects?
- Why does binding to the Picker not work anymore in swiftui?
- Perl lexer: why does "<=>" eq "=" in the context of <=><=><=>?
- Why does asserting on the result of Deref::deref fail with a type mismatch?
- Why can std::function be constructed with a lambda with a different return type?
- Why does HALF_UP sometimes round down with double?
- Why does map work like izip_longest with fill=None?
- Accessing a pandas.DataFrame column name with a '.' in it
- Why does this anonymous function starting with println result in a NullPointerException?
- Why does ProGuard keep the onCreate() method?
- Why does Coverage.py ignore files with no coverage?
- Scala: How to get the result of a Future
- Why does not capitalizing the class name cause a compiler error here?
- Why does TEdit only shows text with length equals or less than 37440 characters?
- Why does ng-mouseover not work with ng-if
- Why does Pip disregard configured repository with nested dependencies?
- Why does odd.fst not work with the filter function?
- why does calling an overloaded function with arguments that don't match still work
- Why does c_str() return the same value for two different strings?
- How to track the depth in this object graph depth-first search algorithm?
- Why does TypeScript mix the module and prototype pattern?
- Django 1.6 + RabbitMQ 3.2.3 + Celery 3.1.9 - why does my celery worker die with: WorkerLostError: Worker exited...
- How to implement a Quartz.NET job in ASP.NET MVC with UnitOfWorkPattern on EF Code first
- (iOS) Why does AVAudioPlayer initWithContentsOfURL always fail with error code=-43
- Why does irb echo the right hand side of an assignment instead of the return value in the case of a setter method?
- What is the smallest feature set to enable polling a future with Tokio?
- How Does WebSphere Choose the Classloading Order in a Folder (WEB-INF/lib)
Only authorized users can answer the Search term. Please sign in first, or register a free account.
tl;dr: use
tokio::time
if there's one thing to take away from this: never perform blocking or long-running operations inside of asynchronous operations.
if you want a timeout, use something from
tokio::time
, such asdelay_for
ortimeout
:what's the problem?
to understand why you get the behavior you do, you have to understand the implementation of futures at a high level.
when you call
run
, there's a loop that callspoll
on the passed-in future. it loops until the future returns success or failure, otherwise the future isn't done yet.your implementation of
poll
"locks up" this loop for 5 seconds because nothing can break the call tosleep
. by the time the sleep is done, the future is ready, thus that future is selected.the implementation of an async timeout conceptually works by checking the clock every time it's polled, saying if enough time has passed or not.
the big difference is that when a future returns that it's not ready, another future can be checked. this is what
select
does!a dramatic re-enactment:
sleep-based timer
simplistic async-based timer
this simple implementation polls the futures over and over until they are all complete. this is not the most efficient, and not what most executors do.
see how do i execute an async/await function without using any external dependencies? for an implementation of this kind of executor.
smart async-based timer
this more efficient implementation hands a waker to each future when it is polled. when a future is not ready, it saves that waker for later. when something changes, the waker notifies the core of the executor that now would be a good time to re-check the futures. this allows the executor to not perform what is effectively a busy-wait.
the generic solution
when you have have an operation that is blocking or long-running, then the appropriate thing to do is to move that work out of the async loop. see what is the best approach to encapsulate blocking i/o in future-rs? for details and examples.