Hacker News new | past | comments | ask | show | jobs | submit login

You'd have to poll something to determine that there was data written to the array, which means you'd need some mechanism (mutex, cv, channel) per entry. If you just constantly spin on the array entries you're wasting time, and you're introducing race conditions (distinguishing partial writes from completed writes). So your array would end up being something like [(bool, str)], with the bool set to true at the end of the write to signal completion.

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.




That's what WaitGroup is for. You can only get the full sorted array when every goroutine is done. You don't need to spin...


But then you can't print them as they become available. Which was one of the two things the original author wanted: Print in order, but don't delay for all of them to be finished. He wants to make N requests, and print all N in the order made, not in the order of completion. And he wants to print them as early as possible, minimizing delay to first feedback (except in the worst case that the first request happens to be the last to complete, obviously).

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.


That's fair. My issue with the requirement is that, if you fire up enough tasks, you only ever get to print a result or two before being blocked until the whole set is done anyway. But if you really want that behavior, my solution doesn't do that, agreed.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: