That later point is a little more complicated/subtle and took me years of threaded programming to learn and accept. When adhering to these two rules, C++ is safe and extremely powerful.
That later point is a little more complicated/subtle and took me years of threaded programming to learn and accept. When adhering to these two rules, C++ is safe and extremely powerful.
Well, nothing, except the simplest of tasks, is pure IO. If you are talking about asynchronous programming, that is basically the cooperative multitasking of the Windows 3.1 era. One event handler will, if it performs a lot of computations, block another from running. Most people seem to forget that the CPU is a resource that can be blocked too. So in the end you still end up spawning threads to reduce latency.
Sure, performance wise it is probably better to have a fixed number of threads which do their own scheduling in userspace but this requires much more work then a simple if(!finished()){yield();} and making a thread per client.
To modify JWZ's famous joke:
You have a problem. You say, "I know, I'll use threads!"
Nowyou prob h2ave lems
The underlying streambuf doesn't provide intrinsics to measure the remaining capacity of the output buffer, and may be forced to flush at any output request -- causing unavoidable blocking.
Of course, it is possible to implement your own streambuf class which provides an interface to measure remaining output buffering capacity. Just something to know...
C++ remains my favourite language; after a couple decades of intensive development using it, pretty much every other language always leaves me feeling "crippled", somehow.
Nginx vs. Apache is a great example of this difference. https://www.nginx.com/blog/inside-nginx-how-we-designed-for-...
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
People don't like it in general, but event driven works for me, mostly. Your mileage will almost certainly vary.
or am i still not getting this?
2.a. is about performance. And while not specifically about C++ this article covers the main idea http://www.kegel.com/c10k.html
2.b. is about avoiding deadlocks and race conditions. Threaded programming in C++ is dangerous. For years I would have said, that I could avoid deadlocks and race conditions by virtue of being a good programmer. However, I've debugged enough of my own code to know this is not always true.
If you only use threads for data driven computation, then you greatly reduce the risks. On the other hand if you have multiple threads running around accessing anything and everything in your program then you need a lot of thread locks which is tedious to implement and not well supported in C++ (vs. say the synchronized keyword in Java), does not perform well and still it is very easy to make mistakes. The point is that there is no reason to let threads run willy nilly because you can do event driven programming in C++ (libev, libevent, libuv) and most programs (or rather most parts of a program) are not computationally intensive.
edit: Here's a great resource on the topic of threading. From the SQlite FAQ "Threads are evil. Avoid them." http://www.eecs.berkeley.edu/Pubs/TechRpts/2006/EECS-2006-1....
It's about Java, not C++, but it's still relevant.
Anyway, I believe we should have the best of both worlds: a language which for the outer layers (the "outer loops" so to speak) uses functional style, and for the inner parts allows imperative style (of course the programmer should make sure that no side-effects remain visible here to the encompassing layer).
> The ST monad lets you use update-in-place, but is escapable (unlike IO). ST actions have the form:
ST s α
> Meaning that they return a value of type α, and execute in "thread" s. All reference types are tagged with the thread, so that actions can only affect references in their own "thread".> Now, the type of the function used to escape ST is:
runST :: forall α. (forall s. ST s α) -> α
> The action you pass must be universal in s, so inside your action you don't know what thread, thus you cannot access any other threads, thus runST
is pure. This is very useful, since it allows you to implement externally pure things like in-place quicksort, and present them as pure functions ∀ e. Ord e ⇒ Array e → Array e; without using any unsafe functions.Never use threads in C++. Gotcha. Good thing I'm learning Rust, then.
However, C++ really isn't that hard to learn. Harder to learn than some alternatives, perhaps, but only like driving a stick shift is harder than an AT, but neither really qualifies as simply hard.