88 points · by ingve · 2y ago · 95 comments
The irony of all of this is that the core thing the post wants to do, of posting results in order to reduce confusion for users, is also probably (I don't know the complete use case, but in general) wrong! Print when you get the results back! Don't block results behind a slow early request! It's a command line program, what's the virtue of queueing fast responses? The only point of the program is to print the output.
> (The specific context is that I've got a little Go program to do IP to name DNS lookups (it's in Go for reasons), and on the one hand it would be handy to do several DNS lookups in parallel because sometimes they take a while, but on the other hand I want to print the results in command line order because otherwise it gets confusing.)
If I was using this program, I too would appreciate ordered results and an early return where possible without breaking the ordering.
Edit: and other similar programs might use a limited pool of workers, in which case the user would want to see ordered results as they came in and they would be expected to complete roughly in the same order they were started in.
Similarly, the existence of others wanting different behavior is also a poor counterargument. The fact that someone wants a Bag doesn't mean that someone else is wrong for wanting an Ordered Set.
Edit: not quite parallel: I mean with a limited pool of workers, or a partial ordering, or something else that means there's a reason to return results early.
The S3 AWS SDK has support for doing chunked/parallel downloads if you can supply an io.WriterAt [1] implementation.
type WriterAt interface {
WriteAt(p []byte, off int64) (n int, err error)
}
The AWS SDK comes with an implementation that has a Bytes() method to return the contents, so you can download faster but you can't stream the results.I created a WriteAtReader that implements io.WriterAt and io.Reader. You can read up to the first byte that hasn't been written to the internal buffers. If there's nothing new to read but there's still pending writes, calls to Read will block and immediately return after the next WriteTo call. As bytes are read through Read, the WriterAtReader frees the memory associated with them.
It provides the benefits/immediate results you get with a streaming implementation and the performance of parallel download streams (at the cost of increased memory usage at the outset).
The first "chunk" can be a little slow, but because the second chunk is almost ready to be read by the time the first is done? zoom zoom.
A consistent structure helps humans parse the output. I have host(1)'s output order in my mental memory.
Or you could just use a sync.WaitGroup and not print anything until all the results are in, which is what the proposed design does anyways in the case where an early request is the slowest to resolve.
Why not wait? Because it’s nice to see results as they come in.
Yes, there are pathological possibilities here, if an early request is slow. But this complaint sounds like a complaint about the author’s goals, which are stated clearly enough. “The author has the wrong desires or goals”, your comment seems to say.
Personally, I’d have written this code using a sequence number as well. Albeit I’d have attached the sequence number to a context. To me, this sound like the kind of problem that contexts do well.
Also, if your stdout is a TTY, but your terminal is not ANSI X3.64? You might be able to look up the corresponding escape codes in terminfo based on $TERM (or simply use tput(1)), but the terminal might not even be able to perform those operations. What do you do then?
If it’s not a tty then you don’t print the ansi escape sequences. Just like how every other well behaving command line utility works.
> Also, if your stdout is a TTY, but your terminal is not ANSI X3.64? You might be able to look up the corresponding escape codes in terminfo based on $TERM (or simply use tput(1)), but the terminal might not even be able to perform those operations. What do you do then?
This feels unnecessarily argumentative but I’ll humour you.
Don’t use $TERM as your only method of fingerprinting a terminal. $TERM is as useless at determining terminal capabilities as the User-Agent string is for determining a web browser’s capabilities.
That all said, the actual ANSI sequences needed to perform the UX I suggested has been standardised since the days of vt100. So even nearly every hardware terminal will support it.
And if you do happen to be running an actual teletype, well you’re in a museum so your use case is very different.
In terms of terminal emulators, most strive for xterm compatibility. And even those that don’t, will still support vt100 sequences. If they didn’t, then even things like readline (and thus Bash) wouldn’t work in their usual expected way.
Sure, the “correct” way to use ansi escape sequences is to query terminfo. But in reality you can get away with hardcoding vt100 sequences for most things. Plus you’ll reduce overhead for your utilities for something that is guaranteed to be supported anyway. In fact perversely, you might actually improve portability because terminfo itself isn’t universal (plenty of non-POSIX systems support ansi sequences but don’t ship terminfo).
Keep track of the lowest received index and print when the next one comes in. Loop the same for the next index if it's already completed.
Or write it in JS where this would be trivial and compile to executable with Deno.
It would not take a lot of glue code to alter the contract to make that happen here.
Task.WhenEach
where you had to use some boilerplate before .NET 9. Nick Chapsas has an interesting youtube video on this explaining what's the problem and what Microsoft did to solve this[1].All you need is the goroutines to report when done via a WaitGroup.
The desired behavior is that printing the first result should only wait for the first result to be available, not for all the results to be available.
package main
import (
"fmt"
"math/rand"
"sync/atomic"
"time"
)
func main() {
args := []int{5, 2, 4, 1, 8}
var indexGen atomic.Int32
indexGen.Store(-1)
results := make([]int, len(args))
finished := make(chan bool)
slowSquare := func(arg int, index int) {
randomMilliseconds := rand.Intn(1000)
blockDuration := time.Duration(randomMilliseconds) * time.Millisecond
fmt.Printf("Squaring %d, Blocking for %d milliseconds...\n", arg, randomMilliseconds)
<-time.After(blockDuration)
idx := indexGen.Add(1)
results[idx] = arg * arg
fmt.Printf("Squared %d: results[%d]=%d\n", arg, idx, results[idx])
finished <- true
}
prettyPrinter := func() {
for range time.NewTicker(time.Second).C {
fmt.Println("Results: ", results)
}
}
go prettyPrinter()
for idx, x := range args {
go slowSquare(x, idx)
}
<-finished
fmt.Println("First Result: ", results[0])
fmt.Println("So-far Results: ", results)
}This will also print some results multiple times. I think Chris wants to print each result once.
This seems similar to JavaScript's for await...of construct https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe....
A while ago I added a golang version here https://github.com/heavyairship/gopherawaitof.
for await of (const name in ips.map(getName)) console.log(name)
Although you’d want more frills to deal with rejections
- Atomic to track print order (name it counter).
- Results slice stores items: {index, err, data}.
- Goroutines: do work, store result, then loop-check if counter matches index to print (with tiny sleep).
Edit: Another solution would be to put printing loop outside with a channel to signal work finished but I don't know how I would avoid using nested loops, one for the items in the list and one to check if the result is back.
Now you're handling the race condition (probably) but you're still actively spinning, which is wasteful if the request takes very long. There's a reason people don't use spin locks much and use mutexes (which may spin, but it's been tuned and doesn't spin forever) instead.
Channels end up being effectively a (bool,str) pair but instead of spinning the consumer blocks waiting for the channel to produce a value. This is simpler, and probably much more efficient than spinning on a boolean variable.
NB: The author wants to print results, in order, as soon as possible, not delay until all results are available. If you can wait for all results before printing, then an array of results + waitgroup works fine. If you don't care about the order, then this can be much simpler.
Literally quoting the OP:
> I want asynchronous execution but to report the results in order, as each becomes available.
99% of the comments in this thread are people ignoring those two requirements. WaitGroup does let you get them in order (store in an array in order), but does not satisfy the second requirement. This isn't hard to understand.
Your worst case scenario is you spawn N go-routines, and they complete 1 by 1 in reverse order from N so your entire dataset is waiting in memory for in-order completion - so no other concern here matters at all.
Task.Supervisor.async_stream(
My.TaskSupervisor,
my_list_of_urls,
&assess_url_exists/1,
ordered: false,
max_concurrency: 100,
timeout: 30_000
)
|> Enum.find(fn
{:ok, {:ok, _url}} -> true
_ -> false
end)
And - that's it. Do I want it ordered? just change the "ordered" flag. Tweaking concurrency? it's there.But the really best part is that any pending computation at the point when the correct result is found, it is automatically cancelled. No waiting for its completion. No memory leaks, no file descriptors left open. It just goes away. Boom.
Just sayin'...
Here, we're discussing implementing future structs just to print DNS results in order. I don't think the UX proposed in the post is good, but stipulate that it is; this is not a hard problem to solve in idiomatic Go.
Reminds me of the time I had to decipher some numerical analysis code written in Common Lisp but in the style of Occam...
Mostly Java or JavaScript devs unable to make a dent in their main programming language space looking for a shortcut to jump to a better paying job by pretending to make a huge difference to the other programming language. I cringe every time a frontend dev who hasn't fully grasped React yet utters the words "I hear Rust is the future. I am going to port a JS package to it..." They have already started making inroads into Golang with half-implemented modules.
Genuinely asking, what would the solution look like in idiomatic Go?
Let's assume for a second that the premise of the article is valid and exactly the behavior we want - "asynchronous execution but to report the results in order, as each becomes available".
Go is to programing what Brutalism is to Architecture. It is striped bare of everything down to the most basic of forms. It is structure is laid bare, put on display and free of decoration.
If you come in and try to write Golang like other languages your going to be unhappy, your going to tell us how go sucks because NPM/PIP/Gems is better (a common lament). It's not defensive rolling up the news paper and wacking new devs to Golang and telling them "don't do it like its java/c/ruby/js/python do it like this..."
Embrace the less is more of Go and it makes more sense and gets much more pleasant.
I often wonder how many of Brutalism's ardent fans grew up in an environment dense with Brutalist structures. I'm not here to bash the movement (the finest examples are wonderful) but just a reminder that the median Brutalist building is often a bleak, bleak affair.
There's probably an analogy in there somewhere for programming too. Perhaps the best of Golang is wonderful but the median just doesn't compare.
ETA: Either way, thanks for the taking the discussion down this direction. Certainly made me chuckle.
This phenomenon exists more broadly in computing and in general, but for some reason Go is a particularly concentrated microcosm of it.
This reminds me of "trompe l'oeil foods"... dishes that appear to be one thing, but are another entirely. Or maybe optical illusions more generally.