by danuker · 3y ago · 0 comments
Coroutines are to me a brain-twisty way to make the most out of a single core, because your language doesn't support multithreading. For example: JavaScript with a single thread in the browser, Python with the GIL.
C++ has threads which ACTUALLY run in parallel on the CPU. Why bother complicating the language further?
That being said, yeah, most async workflows are obtuse and difficult to follow and they force all consumers of your interface to also use the async primitives if they want the benefits. Go seems to be one of the few languages that does async/coroutines right.
See: https://eli.thegreenplace.net/2018/go-hits-the-concurrency-n...
I just looked up Kotlin's co-routines, and there are a number of annoying hoops you need to jump through:
1. Co-routines can only be built by calling runBlocking or coroutineScope.
2. Functions that are async buy should act like blocking calls in a co-routine need to be marked with `suspend`
3. There are a bunch of primitives you need to use like `launch` or `async`.
4. There are built-in options to make the co-routines lazy, but it makes the API feel sloppy.
5. Rather than locks, Kotlin encourages explicit thread dispatching. Some times you need to do this in Go too, like when using a C library, but in general it's rare.
In contrast, the approach with explicit promises and await can be mapped all the way down to a C struct with a function and a data pointer representing a callback. That is, it is C ABI compatible, and thus it can be easily composed across any boundary that respects that ABI.
go func() {
runtime.LockOSThread()
// ...
}()
Is simpler than creating a thread in other languages.Other than confining UI work to the main thread, I don't think I have seen thread confinement as an alternative to locks.
Context switching between tasks has a variable cost, because the implications of the TLB flush depend on the working set size of the switched-to task. If it doesn't touch much memory, the variable cost is low; if it touches a lot, the variable cost can be much, much higher than the register save/restore (fixed cost).
There's also the cost of cache eviction. Not something you have to manually manage, but it's a cost you pay nonetheless. Maybe.
Actual parallelism is surprisingly slow and resource heavy in practice. When everything is on one core, you keep things local in L3, L2, L1.
However, add on a 2nd core, then you suddenly have "ping ponging". Lets say core#0 has data in L1 cache, and now Core#1 needs to read-modify-write to it. That means the cores need to:
1: Core#1 begins to mark that cache-line as exclusive.
2. Core#0 needs to then respond by marking the line as invalid. Then Core#0 ejects the data from L1, and passes it to Core#1.
3. Core#1 can finally begin to work on the data.
4. If Core#0 uses the data again, Core#1 must do step#2 again.
--------
This is called "Ping-ponging". L1 cache read/writes is 1-nanosecond, but ping-pongs can be 30nanoseconds or slower, 30x slower for no reason.
You don't want to add another core to your problem unless you're _actually_ getting a speed benefit. Its more complex than it may seem at first glance. You very well could add a bunch of cores and then suddenly your program is way slower because of these kinds of issues.
Another problem: False sharing. Core#0 is working on "int x", and Core#1 is working on "int y", but x and y are on the same cacheline. So they have to ping-pong even though they never actually touch the same data.
If thread A is going to need to read all the data touched by thread B, then it's unclear why you've split the task across threads. If there are still good reasons, then probably pin A and B to core N (never pin anything to core 0, unrelated story), and let them interleave there.
If that doesn't make sense, then yep, you'll have to face the cost of ping-ponging.
Paralellise it via sharding and I get 80,958,379 transctions per second.
If I remove the randomness, I get 134,600,233 transactions per second. If I parallelise with 12 threads I get 931,024,042 transactions per second.
My point being, if you paralellise properly and do not use shared data, then you can boost performance by a multiple of the number of threads.
https://github.com/samsquire/multiversion-concurrency-contro...
For the technique I use for this scalability, see my journal entries on sharded structs and sharded integers
https://github.com/samsquire/ideas4#565-sharded-struct-pseud... https://github.com/samsquire/ideas4#608-sharded-integers
If you have every tried to implement a complicated iterator you will find that you model a for loop in your head but that the iteration of the loop is controlled from outside using the ++ operator. The ++ operator allows the iterator loop to go one more time round. Normally you have to manage this with state stored in some object. With coroutines you can actually write a loop and co_yield from the middle of the loop to implement the ++ operator.
That said, overhead always needs to be considered; the overhead cost of using a CPP co-routine would be considerable for implementing a state machine that transitions rapidly.
In our code we have an abstraction that wraps a set using a variant. Instead of implementing an iterator/begin/end based on which data the variant holds, we have an iter() method that unwraps the variant and loops through and co_yields. Since you can consume a generator in a for-each loop, you use it the exact same way (except calling iter).
In our case it doesn't save that much complexity, but it's definitely some. I could imagine more complicated cases where it is even more convenient.
However, async/await is real nice as well.
IIRC, a thread takes up ~32kB or so worth of data in pthreads/Linux, or at least... somewhere around there. So on a rather cheap server with 64GB of RAM, you can easily fit 1-million threads. More expensive servers have 512GB, 1TB or more RAM and can easily handle this kind of load.
Of course, coroutines are even smaller/more efficient and can go into 10-million, 100-million or higher.
It does default to 1MB, but these sorts of things are configurable.
Cooperative async runtimes are obscenely efficient.
Because coroutines are easier to think about than threads, and avoid entire (large) classes of bugs.
Because coroutines (typically) have a lower overhead than threads.
Because if you are IO bound and not CPU bound, and therefore you don't need to spread work across cores, threads may not provide a given workload with much, or any, benefit.
I'm working on a post right now covering this in detail, but I spent the last 2 hours being reminded that explaining concurrency stuff in simple terms is hard. :-D
I can buy that. Think about a system thread. It's pretty much its own process that shares an address space with others. Its interface is syscalls and memory. A user thread (coroutine, goroutine, greenlet, whatever) is... whatever you want it to be. It can be small and special-purpose.
You may wonder why OS threads are not themselves sufficient, but it turns out there is a decent amount of overhead involved in managing huge numbers of OS threads. There are limits at which Linux does not perform well anymore, leading to problems like live locking. Also, if you can avoid context switching/cache invalidation by keeping a single OS-level thread busy, you get performance benefits even before you hit OS limits.
So the userspace scheduling and green threading that coroutines enable allow you to increase concurrency without hitting these limits.
There are a few CPU-intensive tasks but those are easy to isolate and send to a threadpool.
Callbacks exist to avoid the overhead of marshalling async results back to the original calling thread: instead of having the calling thread poll until the child thread(s) pass their results back, the calling function returns after kicking off the children, and one of the children directly resumes the work directly when the results are present. This is a significant performance gain.
However, callbacks have famously poor ergonomics, so many structured alternatives have been created: Promises/Futures, Async/Await, and CPP Coroutines.
You could use threads instead, but then you risk getting in all sorts of concurrency problems. And if you synchronize everything, then great, you have reinvented coroutines. In fact, you can think of coroutines as threads with built-in synchronization, which may be how they are implemented.
Seems like different type of concern than what you need multiprocessing for.