News for hackers. Stuff that matters.
Re:Why not C++? by thrownaway2424 on Saturday March 05, 2016 @02:44PM (#11230716)
#2 seems questionable. I always program in a thread-per-request style and start threads for blocking sub-operations of top level requests as well. I know there are platforms where this doesn't work well and I also know a lot of people cut their teeth on dreadful systems like sunos where it took ten seconds to start a thread, but on modern Linux threads are dirt cheap and well worth the clarity that synchronous programming allows.
Re:Why not C++? by zzzcpan on Saturday March 05, 2016 @03:23PM (#11230904)
Synchronous looking programming doesn't offer any clarity for anything beyond dumb sequential requests to a single node, that nobody cares about. Try building a distributed k/v store with that.

It fails miserably once you have to deal with zero downtime restarts for continuous deployment, rate limiting, requests cancellations, waiting for one or multiple responses from multiple nodes, making more requests to other nodes just after a bit of time to guarantee latency, using a lot of different kinds of shared data, like response queues, log queues, connection caches, data caches, all used by multiple clients, while at the same time doing some synchronization of data between nodes, etc.

Anything non-trivial is impossible with threads in practice.

Re:Why not C++? by SamReidHughes on Saturday March 05, 2016 @08:54PM (#11232112)
That's a big list of features, and essentially all of them, or the general ambient complexity that you're handwaving, have been hit by software written in a threaded style. And it wasn't a hindrance. Quite the opposite.
Re:Why not C++? by thrownaway2424 on Saturday March 05, 2016 @03:27PM (#11230928)
These statements are so cute. I can reasonably assure you that the distributed k/v store I have written in the thread-per-request style is currently out there serving more traffic than you've ever dreamed of.

As for your specific points, I disagree totally. Each of those things is easier to me in the synchronous style than in the async style. Certainly something like hedging is way easier.

Re:Why not C++? by CyberDildonics on Saturday March 05, 2016 @05:47PM (#11231460)
Those are some extraordinary claims, but I'm not seeing an extraordinary evidence.
Re:Why not C++? by SamReidHughes on Saturday March 05, 2016 @08:12PM (#11231981)
If you're talking to disk, you'll eventually be doing it synchronously anyway, because on Linux the API's for async disk I/O aren't (weren't?) all there yet. For some time I was working on a product with a command line flag to decide between using a worker pool of threads versus event-based disk I/O, and there wasn't a big enough performance difference (if any, I don't remember) for us to keep the event-based code. If you're getting some fancy PCI SSD's or persistent RAM and really want to minimize latency-to-fsync time, maybe things would be different.

Also, if you use an event loop, you have to do scheduling yourself. For distributed key/value stores, good thread scheduling is even more important. It removes a big amount of technical risk to lean on the kernel's, unless your product is sufficiently minimalistic.

Async will get you real performance advantages for pure networking, but if you're talking to disk it's, when not buggy, not very useful anyway.

Also, as for programming style, even if you want event-based syscalls, cooperative userland-managed threads are a big win over callback hell. The only bad thing about them is wasting address-space on 32-bit systems, and maybe just wasting memory too.

Re:Why not C++? by zzzcpan on Saturday March 05, 2016 @11:58PM (#11232544)
Cooperative threads only introduce confusion and are not making anything easier over threads. For example, the following code will fail if one of the functions yields and global array index changes by another cooperative thread:

   arr_index ++ 
   arr[arr_index].foo = foo()
   arr[arr_index].bar = bar()
There is no protection from this, synchronization primitives are still needed, just like with threads.

Which is not the case with event-driven approach. Event-driven code forces you to write asynchronous functions differently from the rest. There is no confusion of what yields where and returns from where. There are just continuations. So, if foo() is asynchronous in the example above, you wouldn't modify global arr_index across callbacks, you either store its value or modify it in a single callback, because you can rely on callbacks to never get interrupted:

   foo(func(res){
      arr_index ++ 
      arr[arr_index].foo = res
      arr[arr_index].bar = bar()
   })
Furthermore, because of the very specific constraints on callbacks, event-driven approach allows to implement some sort of composable virtual processes, capable of cleaning up and keeping track of various resources and accepting signals from other virtual processes via callback. And it's pretty easy to do, so some event-driven applications in the wild do that, although not always call them processes.

So, again, if you find event-driven programming in any way harder, than multithreaded - you are definitely doing it wrong. Because it completely frees you from thinking about synchronization without adding anything extra that you cannot get used to.

As for disks: there is more than one and you are not talking to them directly, there is a filesystem cache in between. Event loops typically use thread pools to fake asynchronous filesystem access and for other work. And it makes some sense latency and performance-wise, because request that waits for some disk does not block requests that want to access other disks, or hit cache, or maybe it's an ssd and accessing it in parallel is faster.

Re:Why not C++? by SamReidHughes on Sunday March 06, 2016 @02:05AM (#11232794)
> Cooperative threads only introduce confusion and are not making anything easier over threads.

They introduce (ostensibly or in reality) performance, of the kind that obviates a mass of arguments in favor of event loops.

> There is no protection from this, synchronization primitives are still needed, just like with threads.

And it's not a problem.

> There is no confusion of what yields where and returns from where.

This isn't a problem in practice, except when you're (without due care, but it's easy to screw up) migrating from the event-based code that was written with this assumption. You write your code as if it could block anywhere, and then stop wondering whether something could block. If some code is totally not going to block, you use a mutex anyway, hopefully the asserting kind that logs a message if it ever has to wait.

It's easy for code written with callbacks to wind up with baked in, undocumented dependencies of chunks of code that aren't allowed to be split up is far worse to maintain than that which lays out that information explicitly.

Your example with arr_index is a great demonstration of something trivially solvable by protecting the shared field with a mutex. And if you did that, you would easily notice if foo() or bar() ever decided it should increment arr_index.

> Because it completely frees you from thinking about synchronization

Well this is untrue. So completely untrue!

(Edit: Hell, you very nearly showed it in your own examples. Make the first foo() run your foo(func...) example, make that callback get called without waiting in some cases, and bam, you've got a synchronization problem.

Callbacks do nothing to protect you against the class of synchronization problems where the order in which you do stuff matters. For example, naively written rate-limiting code using callbacks will allow incoming actions to pass through out-of-order and might also starve operations that had been blocked. Likewise, you are unprotected from that variable getting incremented when a callback gets called sooner than you'd expect -- and no, on some supposedly high-performance server under load, throwing every callback around the event loop an extra time is not an acceptable option.

Ultimately it's moot -- for sane enforcement of proper ordering, you have to rely on some sort of explicit mutual exclusion.)

> some sort of composable virtual processes, capable of cleaning up and keeping track of various resources and accepting signals from other virtual processes via callback.

And what if I told you that you can keep track of resources and accept signals from, well, anything, in cooperative (or non-cooperative) threads? Because, you can.

> As for disks: there is more than one and you are not talking to them directly, there is a filesystem cache in between.

Sometimes you are talking to them directly. Event loops use thread pools for disk I/O (instead of the event-based APIs on some platforms) because, well, I don't know what other peoples' motivations were, but I can tell you it's more portable and kernels seem less buggy when you do it that way.

Re:Why not C++? by zzzcpan on Sunday March 06, 2016 @08:50AM (#11233743)
> for sane enforcement of proper ordering, you have to rely on some sort of explicit mutual exclusion.

Oh, see, we got somewhere. You seem to presume that it's ok to implement an event loop that doesn't guarantee mutual exclusivity of callbacks. But that's not the case, the whole point of event-driven programming is to guaranty that exclusivity, so you wouldn't have to think about synchronization. So, your arguments do not apply here at all.

EDIT:

> example, make that callback get called without waiting in some cases, and bam, you've got a synchronization problem

There is no such thing as waiting for callbacks in event loops. There is giving up control to a callback and getting it back once it returns. Or it's not an event loop otherwise.

> And what if I told you that you can keep track of resources and accept signals from, well, anything, in cooperative (or non-cooperative) threads? Because, you can.

No, you can't. Because of the way blocking code is written there is no guaranteed state of mutual exclusivity of everything where your signal/message handler can execute and operate in the same scope, without causing havoc.

Re:Why not C++? by SamReidHughes on Sunday March 06, 2016 @03:11PM (#11235337)
> You seem to presume that it's ok to implement an event loop that doesn't guarantee mutual exclusivity of callbacks.

No, that's not what I said at all. How could you even infer that? What I was talking about was, try imagining how you'd enforce a certain ordering of behaviors. For example, a series of requests come in, they're numbered, you have to evaluate them by increasing number. Evaluating them can involve several operations where you have to wait for each of them.

"Mutual exclusion" doesn't mean one thing happens at a time -- it means none of your code gets interleaved. If for one of your requests, you've got to evaluate a(); b(func { c(); });, and you want the effects of a, b, and c to happen atomically relative to the evaluation of other requests, you will have to explicitly manage that.

> There is no such thing as waiting for callbacks in event loops.

"Make that callback get called without waiting [to call it]" means calling it directly, instead of having it be called "later" as with setImmediate in Node.js for example. As you could have inferred if you chose the meaning that led to a synchronization problem, which would be the natural way to read things.

> No, you can't. Because of the way blocking code is written there is no guaranteed state of mutual exclusivity of everything where your signal/message handler can execute and operate in the same scope, without causing havoc.

Yes, you can. And what you say is prima facie nonsense. People have done it, it's not particularly interesting either. And believe it or not, there are ways to create a guaranteed state of mutual exclusivity in blocking threads, not that you necessarily need such a thing in the first place.

Re:Why not C++? by zzzcpan on Sunday March 06, 2016 @05:07PM (#11235787)
> If for one of your requests, you've got to evaluate a(); b(func { c(); });, and you want the effects of a, b, and c to happen atomically relative to the evaluation of other requests, you will have to explicitly manage that.

Well, yeah, you define relationships between them explicitly, by nesting event handlers if you want one to happen after the other one. It's just a matter of a habit. You'll get used to it. It's not that different from placing one statement after the other one in an imperative language.

> means calling it directly

Ok, I understand what you mean. It breaks the whole model though. Instead of calling it directly, callback must be "posted" to be executed by event loop.

Although I admit, I made that mistake myself in the past. Luckily, event driven code is very predictable and unit tests were able to caught it.

Re:Why not C++? by ArkyBeagle on Saturday March 05, 2016 @05:45PM (#11231450)
Having things be designed as event-driven may provide more opportunity for something incrementally more akin to proof of correctness. Add a large quantum of salt and caveat that; it's simply slightly easier that way.

People don't like it in general, but event driven works for me, mostly. Your mileage will almost certainly vary.

Re:Why not C++? by dclusin on Saturday March 05, 2016 @02:56PM (#11230761)
A context switch takes about 50 microseconds. If you want to handle 10,000 requests in a second 500 milliseconds is lost to context switching alone. Probably more. The nature of IO & user input in general is to hurry up and wait. It's usually simpler to do async requests & polling file descriptors rather than thread-per-request. The former seems on the surface more complicated and more lines of code, but IMO, ends up being less complicated because you won't have to spend time digging through logs trying to figure out that the reason some other unrelated thread stalled for so long is because you were blasted with thousands of requests in the same second.
Re:Why not C++? by thrownaway2424 on Saturday March 05, 2016 @03:10PM (#11230848)
Where did you get that number? That's the kind of SunOS derangement I'm talking about. On Linux with NPTL (which is over a decade old) and any recent Intel CPU (Westmere or later) a context switch between threads of the same process takes only about 1-2 microseconds.
Re:Why not C++? by jcoffland on Saturday March 05, 2016 @03:50PM (#11231032)
Regardless, context switching, waiting on locks and the added cost of allocating a stack to each thread are all relatively expensive. I've gotten huge performance increases by rewriting threaded code to instead use non-blocking IO.

Nginx vs. Apache is a great example of this difference. https://www.nginx.com/blog/inside-nginx-how-we-designed-for-...

Re:Why not C++? by thrownaway2424 on Saturday March 05, 2016 @07:23PM (#11231823)
I think these can be and often are combined. You can definitely have an event driven main IO loop accepting connections and reading packets, that nevertheless dispatches whole requests onto their own threads. I work with a lot of services written that way. The fact that you can reuse the frontend for several applications amortizes the cost of developing it as a high performance asynchronous thing.

As for stack allocation I definitely see your point there. It is bizarre that Linux defaults to 2MB or whatever it is these days. I usually work with a 64KB thread stack.

Re:Why not C++? by jcoffland on Saturday March 05, 2016 @03:11PM (#11230850)
This is exactly what I'm talking about. If you want to reach really high transactions rates then you cannot use one thread per transaction.
Re:Why not C++? by thrownaway2424 on Saturday March 05, 2016 @03:20PM (#11230891)
I won't argue that async software thread per hardware thread style will have better maximum performance than a thread-per-request style, but I think that difference will not be material in most applications (the difference between the two styles of C++ server programming being far smaller than the difference between, say, a Go program and a C++ program), and the cost paid in code readability is pretty high. All that async continuation passing makes your code a twisty maze, and that style is fraught with lifetime problems that are the very thing most C++ haters are complaining about. In synchronous style all the allocations are scoped by nature. In async style the programmer has to assign ownership of everything to some master continuation that will delete them all in the final callback. That adds a lot of code.
Re:Why not C++? by jcoffland on Saturday March 05, 2016 @03:32PM (#11230953)
You are right about the added difficulty of resource ownership in the face of asynchronous code. This is a trade off. lambda functions in C++11 can help with this. They make it possible to pass resource allocations (smart pointers) through to callbacks.
Re:Why not C++? by zzzcpan on Saturday March 05, 2016 @03:32PM (#11230954)
> All that async continuation passing makes your code a twisty maze

On the contrary, it gives your code clarity, consistency and predictability.

> some master continuation that will delete them all in the final callback

Even nginx in plain C is not doing that, but simply creates destructors on allocation to avoid tracking stuff manually.

Just don't jump into the first thing you read somewhere, remember one simple rule: if it feels harder than threads - you are doing it wrong.

Re:Why not C++? by SamReidHughes on Saturday March 05, 2016 @08:39PM (#11232074)
> On the contrary, it gives your code clarity, consistency and predictability.

Well, when a product I worked on gradually migrated from event loops with callbacks to threads, clarity, consistency, and predictability made big improvements. Some callback usage would have been better with C++11 or C++14, but it's still way worse than what you can do simply by having variables go in and out of scope on a stack.