298 points · by jtolds · 10y ago · 153 comments
Novices to the language have a tendency to overuse channels. Here is Andrew Gerrand addressing precisely this point two years ago at GopherCon: https://www.youtube.com/watch?v=u-kkf76TDHE&t=815
Neither the referenced performance characteristics via Tyler Treat, nor the FUD surrounding channel-based program architecture, invalidate channels generally. One does have to think carefully about ownership hierarchies: only one goroutine gets to close the channel. And if it's in a hot loop, a channel will always perform worse than a mutex: channels use mutexes internally. But plenty of problems are solved very elegantly with channel-based CSP-style message passing.
It's unfortunate that articles like this are written and gain traction. The explicit instruction to [new] Go programmers is that they should avoid channels, even that they are badly implemented, and both of those things are false.
Wait, why would you say that?
In general, if "orchestrating concurrency" involves guarding access to shared mutable state, then you can't orchestrate it at the callers site. It would be a massive encapsulation leak, because synchronization is not composable, requires special knowledge, plus you don't necessarily know how to synchronize unless you have knowledge about internals. Furthermore, because it is after the fact, your only choice of handling it is by means of mutexes, which has really terrible performance characteristics. Even if you could do ordering by other means, you end up paying the price of LOCK XCHG or whatever mutexes translate to, not to mention that you'll have problems if you want (soft) real-time behavior, because now you can end up with both dead-locks and live-locks.
And this brings us to another problem. If you end up doing such synchronization in Go, then Go's M:N multi-threading ends up doing more harm than good, because if you need such synchronization, you also need to fine tune your thread-pools and at this point 1:1 would be better. On top of 1:1 platforms you can build M:N solutions, but it doesn't work well in the other direction.
> Novices to the language have a tendency to overuse channels
Novices to software development have a tendency to overuse mutexes as well.
What this generally means in Go is that it is an antipattern for your library to provide something like "a method that makes an HTTP request in a goroutine". In Go, you should simply provide code that "makes an HTTP request", and it's up to the user to decide whether they want to run that in a goroutine.
The rest of what you're talking about is a completely different issue.
Channels are smelly in an API. IIRC in the entire standard library there's less than 10 functions/methods that return a channel. But the use case does occasionally arise.
and all this turns out to be a really amazing system of paradigms when designing apps to work in the real world
Shared mutable state is generally behind an API boundary. I'm talking about the exported method set of that API. That is,
func (f *Foo) Update(i int) (int, error) // yes
func (f *Foo) Update(i int) (<-chan int, error) // no
func (f *Foo) Update(i int, result chan<- int) error // noBut channels use locks internally. The choice of channels vs. mutexes is one of design, not implementation. Also, mutexes are blocking; LOCK XCHG isn't. Sure, mutexes also use LOCK XCHG (but so do channels, and nearly all concurrent data sctructures), but they also block (as do channels).
> your only choice of handling it is by means of mutexes, which has really terrible performance characteristics
That's just not true. There is a way to translate any locking algorithm to a non-blocing one (in fact, wait-free, which is the "strongest" non-blocking guarantee), yet only only a handful of wait-free algorithms are used in practice. Why? Because it's hard to make them more efficient than locks in the general case.
> not to mention that you'll have problems if you want (soft) real-time behavior, because now you can end up with both dead-locks and live-locks.
Again, channels are blocking data structures.
> If you end up doing such synchronization in Go, then Go's M:N multi-threading ends up doing more harm than good, because if you need such synchronization, you also need to fine tune your thread-pools and at this point 1:1 would be better.
I don't know where you're getting that. AFAIK, Go's mutexes don't block the underlying thread; only the goroutine.
The question of which concurrency mechanism should be used is a difficult one (and in general, more than one is necessary; even Erlang has shared, synchronized mutable state with its ETS tables), but you are very misinformed about how concurrency constructs are built and about their performance behavior.
If it truly is the accepted best practice for novices to avoid channels, then that PR campaign has been tried and found lacking. EDIT: whoops, read parent wrong.
(I decided to make a new comment rather than edit my existing comment)
Just to add to this, I found the blog post he mentions[1] towards the bottom that supports this conclusion a really good read.
[1] http://journal.stuffwithstuff.com/2015/02/01/what-color-is-y...
There's more to it than I can really describe here, but in effect it allows you to treat a thread as an object with methods; calling a method on the object sends a message to the thread. The thread's main code can, at any point, block and wait for a message, or combination of messages.
The handling code looks like this:
...some code...
accept DoSomething(value: in out integer) do
...some code here...
end
...some more code...
That causes the thread to block and wait for the message. When the message is sent, the caller blocks, the receiver runs the handler, then the caller resumes.The beauty here is that inside the message handler, you know that the caller is blocked... which means it's safe to pass parameters by pointer[]. Everywhere the parameter's in scope, the parameter is safe to use. The type system won't let the thread store the pointer anywhere without copying the contents first, so you get zero-copy messaging and* it's failsafe.
You can also do really cool stuff with timeouts, guards, automatic thread termination, etc. Here's a simple multithreaded queue (syntax and logic not guaranteed, it's been a while):
loop
select
when usage < capacity =>
accept Push(value: in integer) do
data[usage] := value;
usage := usage + 1;
end;
or
when usage > 0 =>
accept Pop(value: out integer) do
usage := usage - 1;
value := data[usage];
end;
or
terminate;
end select;
end loop;
Multithreaded! Blocks the client automatically if they pop while the queue's empty or push while it's full! Automatically terminates the thread when the last connection goes away and the thread leaves scope! Thread safe! Readable!I'd love to be able to do this in a more mainstream language.
[*] This is a simplification. Ada's pointers are not like other language's pointers.
In regards to efficiency, Ada as a language can be optimized to a greater extent than C/C++. It avoids the aliasing problem all together, ALIASED is a keyword in Ada that must be explicitly used, by default the compiler prevents aliasing! Everything else in the language is very unambiguous, a lot of checks are done at compile time, and if needed for performance, run time checks can be turned off on a selective basis.
Combined with the optional but enabled by default since-you-are-going-to-write-them-anyone bounds checking on parameters, and a type/subtype system that lets me ACTUALLY DEFINE the ranges of every parameter going in and out of my function calls, well, whenever I look at a bug fix, I do a mental check of "would this even be possible to do wrong in Ada?" and for about 30% of bugs, I'd say no.
Ada's main disadvantage from an embedded point of view is the hoops it makes people go through to do bit manipulation. It is understandable why, bit manipulation breaks the entire type system in every possible way, but a lot of embedded development requires it. At some point it'd be nice if the language had a keyword that just said "this variable can be abused, let it live dangerously."
It also has proper tagged types and built in syntax for circular arrays. Two bits of code I am sick and tired of writing again and again in C, and then having to explain to people what a tagged type is.
Ada's main flaw is that it doesn't look like C.
Yeah, I used to think it looked bizarre, as someone who grew up with C and C++.
Having spent the last few years doing a lot of Ruby, though, I find looking at it now with fresh eyes it looks quite natural. Aesthetics really seems to boil down to simple familiarity.
But those are quibbles, and at it's heart it's still an excellent, excellent language. And there are Ada compilers in Debian, it's still being maintained, it compiles really quickly into excellent code, it interoperates beautifully with C...
Didn't Ada 2005 fix the OO system to give it the CLASS syntax everyone is used to?
Ada's usual syntax and declaring class inheritance are isomorphic with each other, the transformation a compilers does are the same, but non-JS programmers are used to class inheritance syntax.
I've always wondered if JS programmers would actually pick up on Ada's object system faster, just because they wouldn't mind the lack of an explicit inherits quite so much.
As for GC, I thought it was optional in Ada, just never implemented. For most of Ada's target audience though, heap allocators are already verboten, so GC isn't needed. :)
I'd really like some of Rust's ownership semantics along with Ada's already well developed feature set. Pointer ownership is still a gnarly problem, I don't recall what, if anything, Ada does to help out with it.
> And a less wacky OO system (invisible syntax, ugh).
Not sure what you mean by this one?
> And there are Ada compilers in Debian, it's still being maintained, it compiles really quickly into excellent code, it interoperates beautifully with C...
I came across http://www.getadanow.com the other day. Really easy way to get Ada going on OS X, too.
Old, tatty code but:
https://github.com/IanCal/semq/blob/master/src/messagequeue....
This made message queues that would pause if there was a pop on an empty queue (for long-polling), supports removing everything and if a new 'client' connects while another is waiting for an item sends an error message to the original client. I'm sure there's a neater way of doing it but this sat and ran for quite a while for me and didn't take long to write :)
Generally, the loops are achieved by making an infinitely recursive function call, and you can therefore switch between major behaviours by having multiple functions.
For a quick syntax thing, sending a message is "address ! message" and what I think the "accept" in your code is equivalent to a 'receive' in mine.
You won't have the same type safety, but the general pattern of just blocking and waiting safely is there. It's a fun language, and people seem to be pretty happy with elixr these days too (built on top).
There's some better examples here:
http://learnyousomeerlang.com/the-hitchhikers-guide-to-concu...
Er, yes. It's a stack. Oops. Ta.
The author points out that channel teardown is hard. He's right. Figuring out how to shut down your Go program cleanly can be difficult, especially since calling "close" on a closed channel causes a panic. You have to send an EOF on each channel so the receiver knows to stop. When you have a pair of channels going in opposite directions between two goroutines, and either end can potentially initiate shutdown, it gets messy.
At least in the original implementation, "select" for more than one option was really slow and complex. The single-input case was handled efficiently with generated code, but for N > 1, a very general library mechanism with several heap allocations for each message was used. This means having both a wait for data and a timeout in a select puts you through the slow path. Not good. Someone did an analysis of existing programs and found that N=1 was most common, N=2 was reasonably common, and N>2 was rare. N=2 needs special case support.
QNX interprocess messaging has a similar architecture. But they don't have the panic on close problem, and timeout is handled efficiently. So you can generally shut things down by closing something. As each process is notified about the close, it closes any channels with which it is involved, even if some other process has already closed them. The closes thus cascade and everything shuts down cleanly. Processes that time out at a message receive check to see if the rest of the system is still running, and shut down if it's not.
Go's "share by communicating" would be more useful if Go had Rust's borrow checker, so you could share data without races. Yes, Go has a run-time race detector, but that's only useful if races are common enough that they occur during testing.
It does get messy to do it correctly, but I've found in the end it comes out less messy to have a channel communicating back to the sender that can be closed if you want the recipient to be able to close channel. I haven't needed it very often, but it happens. It still ends up simpler than hacking around the problem by trying to "close" the channel from the wrong end and the resulting panic handling.
For concreteness, at least from what I've experienced, the "messiness" is that if you close one of these channels, you may have to "drain" the other channel lest you let the other side block. If the other side is only using the channel in a "select" block with other options you may not need to but if it ever does a "bare" send you need to wait for the other end to send its close. This can be particularly complicated if for some reason the "draining" process has to do something other than drop the messages on the floor.
Why would somebody use "select" for this at all? I.e., if you were going to write:
select {
case send/receive statement:
statement
...
}
Why not just write: send/receive statement
statement
...
What am I missing? select {
case <- ch:
default:
}It's not 'fix goroutine leak' it's "write the logic you want", it's that simple.
Next, channels are slow, really? Send-receive operation on unbuffered channel typically takes around 300ns. Nanoseconds. 300 nanosecond in exchange of nice and safe way to express concurrent things - I wouldn't even call it a tradeoff. It's not slow at all in vast majority of cases. Of course, if you write that software that do care about nanoseconds and channels becomes your bottleneck - congratulations, you're doing great, and you probably have to switch to C++, Rust or even Assembler.
But, please, don't mislead people telling them, that channels are slow. They could be slow for your exact case, but it's not the same.
I don't really get the tone and arguments of the article. Some of the points are totally valid, but they easily falls into the 'hey folks, be careful about this small thing you may misunderstand at the beginning' category. Pity.
Why not profile to identify which channels are a bottleneck and just replace them with a Disruptor?
Thats ridiculous. I could switch my entire language... or I could just use a lock?
First off, looking at Tyler's post, he measured unbuffered channels taking 2200ns vs 400ns for the lock solution - a 5x speed up. That is a large gain, especially when dealing a program that may have high lock contention. Switch from Go to C++ or Rust my not even gain you that much in terms of throughput - they are both compiled code and moving to either language will only mainly alleviate of magic STW pauses - acquiring a lock likely won't be any faster.
Second, in the point of Game and Player, the logic to handle conditions where players disconnect is still simpler to implement with locks - its 2 lines, and there is no need to bring in sync.Pool, or introduce arbitrary timeouts.
Channels are slower than locks. In more complex applications, channels are easier to reason about than locks, but those tends to be in cases where you care more about message passing than state synchronization.
That is not the only performance-related difference between those language implementations. It's not even the most significant one.
For instance, there is a large difference between a compiler with LLVM's optimizations and one without an SSA backend at all.
https://groups.google.com/d/topic/golang-dev/49VaiLCDbeQ/dis...
(not, of course, in go...)
Do not communicate by sharing memory; instead, share memory by communicating.
This approach can be taken too far. Reference counts may be best done by putting a mutex around an integer variable, for instance.
mutex.lock { x++ }
With a 'lock xaddl x 1' instruction.Example: Perhaps once no instances of an object are in use, you want to remove that object from persistent storage such as a DB.
The service can be asked to unload (close) the file, but it's hard to say whether it's in-use at the time without some kind of reference count to current requests using the file.
It's really quite a pity that Go's channel syntax treats channels as unique snowflakes, rather just being sugar for calls into an interface that would allow the underlying channel implementation to differ based on software needs.
I think the article is well-written, and clearly comes from a place of deep experience and understanding. Good stuff.
I guess the message is: everything has its place; don't make a straight-jacket for yourself.
The OPs critques of the specific design of channels as implemented by Go seem on-point to me.
javascript:(function (){var x = document.getElementsByTagName("img");for (i = 0; i < x.length; i++){x[i].setAttribute("src","");}}());
No one can come up with a single abstraction for synchronization without it failing in some regard. I code in go quite a bit and I just try to avoid synchronization like the plague. Are there gripes I have with the language? Sure, CS theory states that a thread safe hash table can perform just about as well as a none-thread safe, so why don't we have one in go? However...
Coming up with a valid case where a language's synchronization primitive fails and then flaming it as an anti-pattern (for the clicks and the attention, I presume) is trolling and stupid.
After having worked with it a fair bit, however, I'm beginning to really like Promises + async/await (as in ES7, Python 3.4, and C#). It manages to keep most of the concurrency explicit while still letting you use language mechanisms like semicolons, local variables, and try/catch for sequencing. If you make sure your promises are pure, you can also avoid the race conditions & composability problems of shared state + mutexes. (Although that requirement is easier said than done...it'll be interesting to see what Rust's single-writer multiple-reader ownership system brings to the mix.)
Erlang did. Or at least it's as close as possible.
You also have to deal with mailboxes filling up, still have problems with single processes becoming bottlenecks, and the whole system is pervasively dynamically typed which is fine until it isn't.
It is pretty good, but it's not the best possible. (Neither is Go. I still like Erlang's default of async messages better in a lot of ways. I wish there was a way to get synchronous messages to multiple possible listeners somehow in Erlang, but I still think async is the better default.)
You can store receivers in ets table and implement any type of selection algorithm you want or have some process which selects workers. There is no default method, because one default method is not good for everyone and people will complain that it's not good for them. Implementing pools is easy in erlang, I've done tailored implementations for several projects.
> You also have to deal with mailboxes filling up
Yeah, unless you implement back-pressure mechanism like waiting for confirmation of receiving. In ALL systems you have to deal with filling queues.
> I wish there was a way to get synchronous messages to multiple possible listeners somehow in Erlang
You can implement receiver which waits for messages and exits when all are received or after timeout, it's trivial in erlang but I haven't needed it yet. Here is a simple example:
receive_multi(Acc,0) ->
Acc;
receive_multi(Acc,Num) ->
receive {special,Data} ->
receive_multi([Data|Acc],Num-1)
after 5000 ->
Acc
end.(0) In the general case, whatever object you give to a third party, you don't own anymore. And the type checker enforces this.
(1) Unless the object's type supports shallow copying, in which case, you get to keep a usable copy after the move.
(2) If the object's type doesn't support shallow copying, but supports deep cloning, you can also keep a copy [well, clone], but only if you explicitly request it.
This ensures that communication is always safe, and never more expensive than it needs to be.
---
Sorry, I can't post a proper reply because I'm “submitting too fast”, so I'll reply here...
The solution consists of multiple steps:
(0) Wrap the resource in a RWLock [read-write lock: http://doc.rust-lang.org/std/sync/struct.RwLock.html], which can be either locked by multiple readers or by a single writer.
(1) The RWLock itself can't be cloned, so wrap it in an Arc [atomically reference-counted pointer: http://doc.rust-lang.org/std/sync/struct.Arc.html], which can be cloned.
(2) Clone and send to as many parties as you wish.
---
I still can't post a proper reply, so...
Rust's ownership and borrowing system is precisely what makes RWLock and Arc work correctly.
No, it's not. Everything is easier with event loops, because everything is always synchronized. And since it is, there is no need for concurrent hash tables, locks, channels, you name it. There is also no more shutdown and cancellation problems, you get them for free and easier than anything. The only thing left is a __consistent__ API with callbacks. But as long as you go with higher order functions you are not going to have any problems.
Are event loops good at some things? Of course! Are the good at everything. Are you high?
> What if you need to do a compute intensive task on a large data structure?
That's a very specialized thing, not something general, that everyone needs. But either way there is no problem abstracting it away with higher order functions in event loops.
However, everyone will most definitely need networking and doing networking by sharing memory between threads is very very hard. Event loops are much easier for that.
Base on that I can predict that in 2050 I will also read an article discussing channels in yet another language and advocating using mutexes instead...
Edit: If you have web developer toolbar installed in Firefox then it is:
Images > Disable Images > Disable Image Animations
I wish I had the magic power of being able to read text with an animated gif next to it without getting distracted every other word that some people apparently have.
Channels orchestrate; mutexes serialize.
The "for score := range g.scores {" loop runs forever, since nothing ever closes the g.scores channel. I.e., the "range" only terminates when the channel is explicitly closed. Even if there are no current senders on the channel, and even if nobody else holds a reference to the channel (and thus nobody else could potentially create a new sender and start sending on that channel), Go doesn't realize it (garbage collection doesn't help here). The "range" waits forever.
Thus, all goroutines that run this code (via calls to NewGame(), via "go g.run()") will run forever, and leak, as long as something else in the program is running. When the rest of the program is done, Go will correctly detect that all these leaked goroutines are blocked and thus it's a deadlock, leading Go to panic ("no goroutines can proceed") and terminate.
You start a game, and that starts a goroutine that goes round in a loop getting scores from a channel. You have players which also have references to the channel and who put scores onto it.
When all the players have left the only thing that has access to the channel is the game's goroutine. It's not consuming CPU itself because it's simply waiting for something to be put on its channel, but it does still have its stack and other resources, and it now has no way to exit.
You can get this sort of resource leak in lots of ways in concurrent systems, and they all essentially boil down to the same thing, a thread or goroutine, or whatever, is waiting on a resource that nothing else has a reference to anymore, and there is no other way end it.
I do appreciate that the article tries to deflate some of the hype about channels that you see when first investigating Go (I know I bought into it at first). After a little experience, I settled into a pattern of using channels for large-scale and orderly pipelines, and more typical mutexes and conditions for everything else. They have strengths and weaknesses, like all tools.
http://syssoftware.blogspot.com/2015/06/lsub-go-changes.html
--
Normally I have ublock to remove distracting elements.
I don't believe it is, but ultimately click bait is click bait.