159 points · by ingve · 3y ago · 142 comments
Go's whole concurrency model of Communicating Sequential Processes is cool, although seems to be the aspect I question the most. Erlang's Actor Model does seem a bit superior and Go can introduce footguns at points, but I've yet to really investigate the alternatives as much as I'd like.
Also, Beej's guide to network programming https://beej.us/guide/bgnet/html/ mentioned in the beginning really is quite fantastic.
That's the problem with Go in general I think. Much like my experience with Ruby on Rails it seems like once you want to go venture outside the safety of the walled garden you can't. The language is specifically designed to keep you as safe as possible. Great for bottom-tier devs and unmotivated people working on corporate TPS reports. Bad for the motivated engineer. Opportunities like this (to introduce a new idea into the go concurrency ecosystem) are basically impossible.
> Bad for the motivated engineer.
Sounds to me like it's really just bad for the engineer who wants to show off how smart they are through the overcomplicated custom abstractions they build.
Condescending response to condescending comment aside, I understand that those custom abstractions can occasionally be great and have their place, but in practice their value usually starts reversing (yes, reversing, not diminishing) once you need to onboard many engineers frequently (junior or senior alike), which is the case for a big part of tech projects (think big tech, high growth startups, but also open source projects where you want first-time contributors to be able to dive in and solve their issue quickly).
And I'm saying this as a motivated engineer who loves playing with various languages but uses Go for most serious things.
(Funny aside - somehow, Google managed to turn Rust into abstraction hell: https://fuchsia.googlesource.com/fuchsia/+/refs/heads/main/s...)
It's usefulness for producing something that works well quickly is great. The second you want to take some time to explore it simply punches you in the face and sends you to the back of the line. In some sense, I guess, Go just offends me.
It's good for the motivated engineer, because instead of running off and creating architecture astronautical wonders of over-engineering, they are getting down to business and making progress to a goal.
Your bottom-tier engineers aren't going to be any better in Go than they are going to be in Java.
Maybe in theory, in practice you get people writing their own implementation of generics with codegen and Canadian aboriginal syllabics…
I personally find myself choosing go because I feel I am way more productive with the language. By keeping me constrained, I have less choices to make on how I solve the problem, and focus more on solving the problem.
What's the issue with making Go good for the lowest common denominator developer? This is fantastic for businesses as they can get new developers productive within a few days. It's great for the ecosystem because the barrier of entry is low.
Just because it's made simple and easy to pick up doesn't mean you can't write complex software with it. It's a programming language, you can write whatever you want with it. If it makes writing complex software easier, then that's a good thing. The only reason why someone would think that's not a good thing is their ego because $FAVOURITE_LANGUAGE has 10x as many language features and 10x as many ways to do the exact same thing.
What is this walled garden you think exists that prevents motivated engineers from doing good work? I like to think of myself as motivated and Go is the reason for that. It made writing complicated concurrent software so much easier for me, and it made reasoning about them so much easier. I do not understand this criticism of Go.
Compare say Java 5 code written with raw servlets implementations and JDBC calls versus modern Spring code. The implementation of the former is easier to understand because everything is very explicit, but the intent of the latter is far easier to understand, since the boilerplate is mostly gone, allowing the actual business logic (what you care about 90% of the time) to be obvious. And you can of course see the implementation if you need to
Simplicity is much harder than complexity. Anyone can add and anyone can subtract recklessly, but it takes genius to subtract without losing too much in the process. The genius is in identifying the essential complexity in a problem and finding ways to dispense with incidental complexity.
I've personally been using Rust more lately for various reasons, but I really do like Go and think its choices are excellent for its niche. In any case simplicity can be practiced in any language by choosing the most straightforward way to achieve things and avoiding over-engineering. Rust has a lot of features and paradigms but I can be productive in it by remembering that just because it's there doesn't mean you always have to use it.
The problem with kitchen sink languages is that someone on the team will use a feature you don't know about.
If enough people on a big enough team do that the project inexorably moves towards the most complex representation of any idea.
On solo projects, some of the most complex languages can be used by effectively by a newcomer. On any other project with the same stack, you need to add in significant ramp up time.
There are two main competing fallacies in developer culture: the first one is that complexity is a good thing, the second one is that complexity can be avoided.
They are both equally wrong, complexity is a curse, but that's the curse of the real world and if you try to hide that under a rug and call that “simplicity”, then everybody is gonna have a bad time. This blog post is a good dicussion on that topic:
https://fasterthanli.me/articles/i-want-off-mr-golangs-wild-...
Abstraction is the only way we can combat complexity (and as mentioned, most of that complexity is essential that can’t be reduced further), so if a given language sucks at it, it sucks.
And he didn't say lowest common denominator developer, he said something like junior Google developer.
And IIRC he said it somewhere in his blog, called command-central.blogspot.com or some such.
It is not a problem that Go manages more developers to perform well. It is a clear advantage. Thinking it is a problem says something about lack of maturity.
Garbage collection is another such example. Compare that to e.g. rust's model which hoists the understanding of lifetime to the engineer, while encumbering the compiler with the dirty work. Whereas golang asks the engineer to do neither (granted golang came later, so maybe they didn't think it was possible).
Would I recommend Go to someone as a first language? Absolutely not. Would I professionally recommend Go to a company in order to lower the skill ceiling to floor, keep seniors+ in check, and keep juniors safe? Yes. That is all it is good at. Everything else it offers another language does better.
I have about a decade and a half of experience as a software engineer. In almost every case, over a long enough time period, a centrally dictated constrained system is almost never ideal. I've ported more companies off Ruby on Rails onto something sensible than I can keep count of. I imagine I will be able to charge $150/hr to do that for companies who bought into Go in about 10 years as well. Once you need to reach outside that box to do a very bespoke task your company needs you're stuck. With RoR I found this to be the case with ActiveRecord. With Golang I imagine it'll either be the concurrency model or the stiff parameters for nearly every aspect of the language. My present company is already at that stage. Their answer was to build around it. So now we have a hodge-podge of tooling in a couple languages and all benefits of a centrally governed language have gone out the window.
These days I generally recommend most people run Python as it seems the most future proof. I've also recommended a few companies move back to Java due to constraints Python could not solve for.
Since I'm probably very average, I'd rather be safe from having to deal with the mess left by bellow average work. So for me it goes Go for work, and a lot of Forth, Lisp (Scheme and Racket mostly), Elixir/Erlang on my own time. Whatever doesn't need to touch other people's work can be malleable as possible. If it gets publicly pawed at, I need carbon steel rails thank you very much.
Further, the idea that Go is somehow bad for motivated engineers doesn’t match my experience and it doesn’t explain the proliferation of interesting tools and services (much of the container / devops ecosystem). I think your mistake is assuming that the only kind of motivation/creativity/etc involves tinkering with language runtimes and that someone who is building original things like Docker, Terraform, or Kubernetes must be “unmotivated”.
[0] https://elixir-lang.org/blog/2016/07/14/announcing-genstage/
If you send to a remote process, and the dist buffer is full, you'll be suspended. (Or you can send with no_suspend, and drop rather than suspend).
When you send to a local process, you need to lock that processes's mailbox, which offers a little bit of backpressure if there's contention. Doesn't provide backpressure when the recipient process is just ignoring its mailbox, though.
IIRC, earlier releases, maybe around r12-r16 would penalize processes that sent to a local process with a big mailbox, but I think that was removed because it didn't really work as envisioned, so better not to have the complexity.
There's ways to build systems that are resilient to large mailboxes, but it's not necessarily simple.
It was motivated by a need to eliminate OOM errors and supports large scale operation at very low latency.
Making it the default is a good design choice, but mandating them isn't: sometimes you don't want backpressure and buffering is what you want, and with no unbounded channel, you easily end up with being an unbounded amount of goroutines instead… (it happened to me once earlier this year)
There's one special thing that Haskell threads have that I think I've only seen in Erlang: it's safe to kill threads. Things will be cleaned up properly. You can safely expect that Haskell code created by someone else has been written to not go into a bad state if it's suddenly cancelled.
For example, you can write a generic timeout function that works by launching the work in a new thread, then wait N seconds, then kill that thread if it's still running. You don't need to make any kind of signalling thing where you send "please stop" message to a Goroutine.
The article talks about Goroutines in context of serving lots of requests. I like to think Haskell's threads and the fact that you can kill them safely makes it much easier to develop servers or job orchestration with simpler code.
I am mostly a Haskeller (10 years now) but I used Go at a startup once. It was shocking how often we leaked goroutines. Whereas in Haskell, if you use async it's hard to.
Haskell exceptions are tricky (and there are plenty of bloggers who make a niche living acting like they're so hard to deal with you need to hire them) but in 2023 it's trivial. Just use the unliftio wrappers and you're golden.
if a goroutine doesn't select on a chan, you're screwed
and don't get me started on how bad Go gets in terms of exception safety. I've seen defer go wrong in so many ways. Unrestricted mutability is mostly to blame.
for item := range channel {
// code goes here
}
becomes for {
var item Item
var ok bool
select {
case <-ctx.Done():
break
case item, ok = <-channel:
if !ok {
break
}
}
// code goes here
}
(If you have a solution to this pattern, please do share! I would _love_ a better way.)That code is written like that because it's the only way to write code like that. You have a channel producing items, it will produce items for as long as the channel is open. You have a context to propagate cancellation.
You code gets bigger but it doesn't explode in size as this boilerplate is static in size regardless of what computation you're doing with those items.
You can improve that code by the way by fixing a bug and reducing the lines.
L:
for {
select {
case <-ctx.Done():
break L
case item, ok := <-channel:
if !ok {
break L
}
// code goes here
}
}
If you think there's a way to write that code any more concise than that, then there isn't. I don't see how this is an issue. The fact that there's pretty much one way to write this code makes it so much easier to parse when reading code that uses this pattern. To me, that's great. var errClosed = errors.New("closed")
func doAThing[T any](ctx context.Context, c chan T) (T, error) {
// the generics are not necessary, but they're also not awful for
// DRYing up this type of a select.
select {
case <-ctx.Done():
var empty T
return empty, fmt.Errorf("could not doAThing: %w", ctx.Err())
case item, ok := <-c:
if !ok {
var empty T
return empty, fmt.Errorf("channel of type %T is done: %w", empty, errClosed)
}
return item, nil
}
}
// ... and later...
for {
item, err := doAThing(ctx, channel)
if err != nil {
break
}
// code goes here
}
I dislike labeled loops, naked returns, and else statements, so this is the pattern I use. func streamingApply[T any](ch channel[T], fn func(T)){
for {
select {
case <-ctx.Done():
break
case item, ok = <-ch:
if !ok {
break
}
fn(item)
}
}
}
For everyone that's complained about generics being introduced to go...It really does help clean up this type of repetition.That being said, my experience is that anything moderately sophisticated requires the use of for/select. In my opinion, that's fine, because select gives you so much power the somewhat more complex form is worth it.
Now if you cant use another language, change project. Go is not perl nor python, it's a sophisticated C. Use a sophisticated C for the wrong project / product and you'll want to kill yourself.
for item := range channel {
_, err := process(ctx, item)
if err != nil {
return err
}
}Thank you!
Before Loom there was often a case to pick Go just for goroutines but that time has passed for me at least.
Go still has it's place in my toolbox, namely shuffling bytes from one fd to another when such a task is called for in an environment where the JVM would be too cumbersome or I just want redistributable binaries for one reason or another. (though Rust is increasingly consuming these use-cases for me I really don't like async Rust)
The call out that Loom doesn't currently do forced preemption/time-slicing is notable though, for now you should make use of platform threads for CPU-heavy parallelism if you have tasks that simply won't yield. The fact you can still just use platform threads whenever you need them largely obviates that from being impactful.
Not true in .Net world as async and Tasks were available since long time ago.
Java is conspicuously absent from the list of languages above. Until now, you've had to either spawn an unreasonable number of threads or deal with Java's particular circle of callback hell. Happily, JEP 444 adds virtual threads, which sound a lot like goroutines. Virtual threads are cheap to create. The JVM schedules them onto platform threads (real threads the kernel knows about). There are a fixed number of platform threads, generally one per core. When a virtual thread performs a blocking operation, it releases its platform thread, and the JVM may schedule another virtual thread onto it. Unlike goroutines, virtual thread scheduling is cooperative: a virtual thread doesn't yield to the scheduler until it performs a blocking operation. This means that a tight loop can hold a thread indefinitely. I don't know whether this is an implementation limitation or if there's a deeper issue. Go used to have this problem until fully preemptive scheduling was implemented in 1.14.
TIL, I would've thought from that description that virtual threads and goroutines were identical, but looks like I have an outdated mental model of goroutines from the <= 1.14 era.Few people realized what callback hell was. Web devs got lucky they added await to JS.
I always appreciated Go for its coroutines. Does make for simpler code.
You know a language has done well when the biggest consistent argument is that it’s “boring”
"Don't communicate by sharing memory, share memory by communicating" from go proverbs[0].
And in the article, "When you create a goroutine, you're essentially allocating a closure and adding it to a queue in the runtime."
Because of this it becomes very easy to share memory by mistake and you end up with bugs. On the other hand Elixir's design makes this kind of thing very hard to do by mistake.
i.e. on a net.Conn one can use SetReadDeadline() to unblock/cancel a Read().
The fact that IO blocks, and also doesn't work with the select statement, means you need to spin up a mess of extra goroutines in some situations. There was some good prior discussion of this here: https://news.ycombinator.com/item?id=13331284
Concurrency and async is my favourite topic.
I think event loop programming is very interesting, and Goroutines mean every process is effectively an event loop. So I like server programming. I have an epoll server that multiplexes multiple sockets per thread which is a bit more scalable than a thread per socket. I like nodejs libuv, but I think we can go further.
I wrote a very simple toy lightweight 1:M:N (1 scheduler:M kernel threads:N lightweight threads) thread scheduler in C, Rust and Java.
https://github.com/samsquire/preemptible-thread
It works on the principle that hot loops can be interrupted BY ANOTHER THREAD (the scheduler thread) on a timer by setting a loop to its limit, to give lightweight threads a chance to execute.
What I think I want today though is an extremely rich process/concurrency API that resembles a stream API but for processes. For example, we should be able to create pipelines that can be paused, resumed, forked, merged, drop_while, iterate_until and whatever else would be useful.
I'm really surprised to hear this called out as problematic. It's actually one of the most efficient aspects of fork() IMHO. COW is almost ideal is it not?
The real problem with fork() is that the entire virtual address space has to be cloned. In practice this means that it's hard to avoid overallocating/overcommitting physical memory, which in Linux anyway leads to OOM of random processes. That is truly awful.
He also goes on to note that threads are lighter than processes, but the author neglects to mention clone() in Linux. I think that an article written in 2023, hailing goroutines as an alternative to multiprocess server architecture, is severely lacking.
> Threads do still have a substantial cost though, and you'll run into scaling problems if you create a new thread for every connection
Depends on the threading model, doesn't it? ref. Solaris
I appreciate this article but it lacks quite a lot of depth. Reads like a first year student's inner monologue. Which is great, but I'm surprised it has gained HN traction.
Occam is probably the most important totally forgotten thread of programming language development.
I would suggest reviewing the Hoare book on CSP, it’s very readable.
I'm not downplaying anything; I'm expressing merely that with a title like "Goroutines: The concurrency model we all..." makes it sounds like go invented something new, but afaict, they're just a well-engineered implemention of already well-understood concurrency principles.
When it comes to concurrency I think it's good to go through the curriculum:
- main loop + interrupt handler
- processes (fork)
- multi-core concerns
- threads (now is a good time to learn about mutex, semaphore, critical section)
- lightweight threads (fiber, coroutines, green threads): learn how they are different
- async/await statemachines written by the compiler
Ok, now we have the background info to make wise choices and call things by their generalized names to avoid holy wars.
We could use a time-faking library, but sometimes this is unavoidable if some dependency, whether from a 3rd party or in stdlib, depends on reliable timing.
I'm wondering how other Go devs approach this.
https://go.dev/doc/articles/race_detector https://go.dev/blog/race-detector
It only logs when a race condition happens, and it may have a non-negligible impact on performance, but it should print useful info to aid in debugging.