by hedora · 2y ago · 0 comments
At least old-school syntax like “GOTO foobar_step_23” and “LABEL foobar_step_23” is grepable).
I greatly prefer programs that “color” functions sync/async, and that use small state machines to coordinate shared state only when necessary.
Go technically supports this, but it doesn’t seem like it is idiomatic (unlike rust, the go compiler won’t help with data races, and unlike C++, people don’t assume that the language is a giant foot-gun).
Any language that supports true multithreaded parallelism provides foot-rail-guns, no matter if you’re locking, asyncing or channeling. For concurrent data structures, you can’t lazily rely on the compiler to catch your errors. Not even in eg Rust. You should never sprinkle concurrent primitives just because.
For every channel created, you need to determine how the invariants of both the channel itself and the contents that pass through it. This is, for the most part, an easier exercise than with locks, because channels provide a way to think about ownership, and crucially, transfer of ownership between threads (goroutines). It also decouples the response to an event from the production of it, whereas with locks you have to dispatch the “next action” from the code that produced the event. I’ve never had a language that’s so easy to do things like “spin up 10 concurrent requests at a time with individual timeouts, cancel outstanding requests if any of them succeeds or canceled by the user, and ensure all tasks are torn down before returning”. It’s near-trivial to get right with channels, contexts and waitgroups.
In either case, since concurrency is so difficult, I would say that the Go docs and resources are quite lightweight on how to use their primitives correctly. Right now, it’s a bit “now finish the rest of the fucking owl”. You need discipline to use them, but there’s no parental figures around to tell you how to watch out for the dangers.
All parallel execution is asynchronous, but not all asynchronous execution is parallel.
async/await interleaves execution in a cooperative fashion: a "fiber" runs until it yields by doing something blocking (such as blocking I/O, the most often cited use case). There are no data races and no need to use synchronization primitives since there is never a case where 2 fibers modify a piece of data at the same time: because execution is interleaved, the operations are always ordered one after the other. Whenever a fiber blocks, execution is returned to the scheduler, which resumes execution in one of the other fibers which were blocked.
fork(pthread_create)/join(pthread_join) parallelizes execution: a "thread" runs until it is done or is killed externally (the scheduler can also pause execution). A thread X can wait for another thread Y to be done by calling join(Y). There is a need to use atomics or other synchronization primitives such as channels (or mutexes, or barriers, or semaphores) when 2 threads share a variable in order to make sure only 1 at a time modifies, because although threads can be ran in an interleaving fashion (and sometimes they are interrupted (pre-empted)), they are usually ran in parallel on different CPU cores/threads (if you have a SMT CPU, which most nowadays are: n CPU cores and each CPU core has 2 "CPU threads").
P.S. A CPU thread != OS thread
e.g. in C#, the following is true:
using var http = new HttpClient() {
BaseAddress = new("https://news.ycombinator.com/")
};
// Runs sequentially
var page1 = await http.GetStringAsync("?p=1");
var page2 = await http.GetStringAsync("?p=2");
// Submitted sequentially, everything after the first yield completes in parallel, IO does not block the caller
var page3 = http.GetStringAsync("?p=3");
var page4 = http.GetStringAsync("?p=4");
// Waits for page3, then page4 to complete, they are effectively parallel
DoSomething(page1, page2, await page3, await page4);
But in Rust, this requires explicit join handle, and if you would like to parallelize/fork the execution flow - you have to schedule a separate task. It requires more effort but in return you get lower async overhead, which is critical for areas Rust is applied to (and host-starting Tasks or Futures would not be easily compatible with borrow checker I presume).> async/await (as most commonly implemented)
Javascript is famously single threaded, which is probably the runtime on which most async/await code runs today.
But yes, Rust for instance has the Tokio async runtime which is parallel, although it also has cooperative async runtimes.
For those who are reading this and feeling unsure: Go has parallel execution, and it calls `fork()` `go`. Go doesn't feature a `join()`, for that you must use channels:
func main() {
done := make(chan bool)
go func() {
fmt.Println("goroutine running")
time.Sleep(2 * time.Second) // simulate some work
done <- true
}()
<-done
fmt.Println("goroutine finished")
}
Funny thing: if you have a goroutine which is waiting to receive some value from a channel, but it never does this, and the other handles to the channel are gone, you get a goroutine leak! The goroutine is blocked, and unrecoverable/unkillable.But later you mentioned threads running in parallel on different CPU cores.
The way I always understood it, is that this is the only real form of parallelism able to happen on a CPU. But that does seem kind of incompatible with your statement at the beginning.
Individual CPU cores are parallel because they are executing multiple instructions simultaneously (even though they are from the same instruction stream).
As sibling notes, you have it exactly backwards. It should read "All parallelism is concurrency, but not all concurrency is parallelism." I thought maybe this was a typo, but then you said:
> If you just think of concurrency as an instance of parallelism, you start to realize there are many ways to achieve concurrency, and thread-safe queues are one of the better ways to do it.
This is demonstrating parallelism as an instance of concurrency, not the other way around. A thread-safe queue can be processed by multiple tasks running interleaved in a single thread in which case it is executing concurrently, but not in parallel.
> Individual CPU cores are parallel because they are executing multiple instructions simultaneously
This is an implementation detail of the CPU. Not all CPUs execute instructions in parallel.
The other way around. Alternating two executions on one CPU core is concurrency, but not parallelism.
This just sounds like badly written chaotic code. Unfortunately there are some people who seem to think "Go has channels, therefore, I need to use channels as much as possible", but that's almost always a mistake.
Channels shouldn't be used very frequently, but they can be very handy especially in combination with select and/or buffered channels. Usually there should be a clear and "obvious" API.
There's a linter which I like[1] that checks variable name length based on the scope of its usage.
The idea is a variable name can be short if it is used in a small lexical scope (e.g. a function parameter in a one-line function) because it won't affect readability much. But names should be descriptive if used in a larger scope (e.g. a constant used across a file).
For example, lets look at "string". Most examples are gonna just call it a "str" or even "s". But if what you have is someone's name you should get called out for calling it a "str" rather than "name".
You shouldn't name all your mathy variables x, y, i, j.
You shouldn't name your channels "chan" or "c". Unless its just generic channel code.
I don't mind short domain variable names. But "chan" isn't that. It's like calling all your ints "num" or all your strings "str".
In Go you can use a type alias to make this work:
type ExitChan <-chan nil
Unfortunately it doesn't really enforce anything at the compiler level, but at the very least you can grep for it.
Unlike GOTO, there isn't really a better alternative for synchronizing parallel programs. Parallel programming (or even concurrent programming, for that matter) is just harder than sequential programming, and if you don't know what you're doing (regardless of whether you use channels or not) you're going to end up with a mess. Channels help to tame parallel programs, but they can't compensate for programmers who don't know how to write correct parallel programs.
And while Rust can prevent against data races, data races are a tiny sliver of parallel programming bugs. Far more common are race conditions and deadlocks, against which Rust is powerless.
> I greatly prefer programs that “color” functions sync/async, and that use small state machines to coordinate shared state only when necessary.
Async/await similarly doesn't solve the problem of undisciplined programmers making a mess. If you give undisciplined programmers async/await and shared state, they'll make a mess as easily as they will with goroutines and channels. If you're hiring people who can't be trusted with shared memory parallelism, then you have to take away parallelism or mutability or you have to train them to write correct parallel programs.
Notes On Structured Concurrency goes into some depth on this comparison:
https://vorpus.org/blog/notes-on-structured-concurrency-or-g...
If channel sends are being used as invocations, then this description can apply just as well to channels as it does to the go statement.
Yeah, this is why we use `sync.WaitGroup`s and similar abstractions in Go. Using bare channels (like using `goto`) is fine for small local things, but if you're building abstractions you should use patterns like those discussed in the article (for example: https://go.dev/play/p/UoB8ECDbaTw --I'm sure this can be abstracted further).
With async/await, everything is still a function. Your IDE and debugger help you understand when and where a function is called. When debug-breaking on a function you have the stack trace.
Async/await gets you fast context switching for IO ops as it is a single OS process (no threads for the OS to constantly switch).
But once you go beyond a single OS process, then you need something like messaging or shared memory on top of async/await to communicate between OS processes/threads.
I think Golang jumps straight to messaging which is better for multiple cores, but misses the first step of async/await which is easier to reason about when you have a single process on a single core.
Also the link to SliceTricks goes to stale content
We don't need to have one language to rule them all. Its fine for languages to make different choices and trade-offs.
It's a weird cult-like thing.
And go is reaching the point where like Java it gets crammed down your throat. Which is probably why golang should start adding even more features
It took me quite a while (years) to go from thinking that returning error (conventionally as the last return value) was a bit clunky to thinking that this is actually a very good idea. I don't mind the if err != nil pattern. I can't think of a single experienced Go programmer that is sufficiently annoyed by this to complain. I sometimes see people new to the language complain about this, but it tends to fade as they adapt.
With the ability to join errors, do sensible comparisons etc, errors work well for me when needing to express high level errors and their low level root causes. (eg the high level error may be "failed to read configuration" and the root cause might be "permission denied when opening file X").
I've come to realize that I like Go style errors better than exceptions for two reasons. First off, a lot of code in, for instance, Java uses unchecked exceptions. Which means that the whole idea that you have to handle exceptions goes out the window.
This, of course, varies from codebase to codebase, but the it is common enough that having exceptions available in a language doesn't mean people will use them in a way that forces discipline. Which kind of makes exceptions pointless. They just become syntax for emitting and handling errors. And awkward syntax at that. Which is the second reason. Exceptions tend to introduce extra scopes you have to deal with. This is annoying and in some cases it can get somewhat complicated.
Exceptions, the way they are commonly used, are a weak enforcement mechanism made more dangerous by people pretending it isn't. If you want discipline, neither exceptions nor Go errors are the way to go. You probably want to look to something like Rust.
I have a hard time seeing how exceptions would make Go better. Yes, if someone could come up with some syntactic sugar for Go 2 to deal with errors, that would be nice, but I have seen no proposals for this that represent actual improvement.
`if err != nil` is actually extremely readable and to justify new syntax for expressing this it would have to be a _lot_ better. I'm open to listening if people can come up with something.
Exceptions didn't end up doing what people hoped it would do in Java. We should learn from that and try not to pointlessly repeat this mistake. Besides, Go has already made its choice. Retrofitting it is only going to do harm.
I think exceptions are pretty much a dead letter in new language designs at this point? You could get people on board for real algebraic types and matching.
Exceptions are a smaller deal than async/await. Basically instead of manually writing "if err" everywhere, it's implicit if you aren't catching it. The most popular languages do this. Rust "?" syntax is also a decent compromise.
The parent is really complaining about idiomatic Go. Which is fair, because idiomatic Go feels like writing Java 6 (that is to say, making lots of compromises due to limitations of the language).
No. An exception is a datatype. Not completely unlike an error type in concept, but intended for erroneous conditions that could have theoretically been caught at compile time (i.e. the programmer screwed up), as opposed to conditions that are not decidable at compile time (i.e. something happened in the outside world).
In Go, panic creates an exception, which may be the source of your confusion. The exception contains any metadata you passed to panic along with other data, like a stack trace. This is not panic in and of itself, though.
> but when writing idiomatic Go one would prefer error types over using panic
Not really. Idiomatic Go says that errors are in no way special and is faulty to think of them as being special. They are just values like any other. Go exceptions allow attaching any value as metadata.
The official line is that panic stack traversal should not cross package boundaries, but internal use is perfectly acceptable. Even the Go standard library does it.
There are multiple ways to use channels wrong, the compiler will not help you and most of the docs and "tutorials" will not cover that. The best thing you can do in Go is stay as far away from channels as you can.
The worst is when people use channels simultaneously with mutex.