8 ms·
Why not C++?
- jcoffland 11y agoC++ is still a fantastic language. It's hard to learn to use it effectively but once you do you have one of the most powerful programming tools available under your belt. The two main points to using C++ effectively are 1. you must protect allocated resources with smart pointers and 2. threads should only be used to exercise multiple CPU cores and never as a way to work around blocking IO. 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.
- allcentury 11y agoAny reading you'd recommend regarding your second point? I've never heard that about C++ before.
- stefs 11y agoi think this is strange. i'm not a c++ programmer, but the evented frameworks (node.js or vert.x) are doing it the other way round: use threads only for IO (or computation so heavy it's practically blocking). the complete opposite.
- misframer 11y agolibuv (used by Node.js) uses epoll, kqueue, etc. for network I/O. It uses a thread pool for all file operations.
- stefs 11y agoah, well - when reading "blocking io" i first thought about the file system. so does my point still stand? using a threadpool for disk IO does go against "threads should only be used to exercise multiple CPU cores and never as a way to work around blocking IO." or am i still not getting this?
- jcoffland 11y agoActually node.js does it the same way. Under the covers node.js handles IO with libev which is an event library.
- misframer 11y agoThey use libuv now.
- deleted 11y ago[deleted]
- jcoffland 11y agoThere are really two parts to point 2. 2.a. is about performance. And while not specifically about C++ this article covers the main idea http://www.kegel.com/c10k.html 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.pdf http://www.eecs.berkeley.edu/Pubs/TechRpts/2006/EECS-2006-1....
- deleted 11y ago[deleted]
- brobinson 11y agoThis paper by the guy who runs Mailinator is really interesting: https://www.mailinator.com/tymaPaulMultithreaded.pdf https://www.mailinator.com/tymaPaulMultithreaded.pdf It's about Java, not C++, but it's still relevant.
- exprI 11y agoI mostly agree. 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.
- jcoffland 11y agoI bet I could name a few things about C++ you probably don't know. One small example, with out looking it up can tell me how to add a prefix operator (e.g. ++) to a class vs. a postfix operator? The answer is ugly. There are a lot details to C++ (and I'm only talking about C++98 at this point). It's easy to learn enough C++ to create some programs but it's hard to really learn C++.
- SamReidHughes 11y agoYes. And even if I didn't, it would be easy enough to look up, and there's no danger to me for not knowing it. That's not where C++'s learning curve has its sharp edges.
- ape4 11y agoThe obvious reason to use threads... so you can do multiple things simultaneously.
- jcoffland 11y agoThis statement misses the point. What I am saying is only use threads to compute things simultaneously and not to perform IO operations simultaneously.
- ape4 11y agoI understand what you saying but its too strict. Say the things you want to compute simultaneously involve IO. For example your application has a window that displays a log by watching for writes to the end of a log file (like tail). This is easy and reasonable to do in a thread.
- thrownaway2424 11y ago#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.
- dclusin 11y agoA 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.
- thrownaway2424 11y agoWhere 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.
- jcoffland 11y agoRegardless, 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-performance-scale/ https://www.nginx.com/blog/inside-nginx-how-we-designed-for-...
- amelius 11y agoThis works, until you start coding an imperative-style interpreter in the functional language, and mess everything up again :) 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).
- chriswarbo 11y agoTake a look at Haskell's Single Threaded (ST) data type, which does exactly this: https://wiki.haskell.org/Monad/ST https://wiki.haskell.org/Monad/ST
- vamega 11y agoST is the efficient version of the State Monad. Where did you come to think that St was short for single threaded?
- chriswarbo 11y agoFrom https://wiki.haskell.org/Monad/ST https://wiki.haskell.org/Monad/ST > 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.
- groovy2shoes 11y agoTake a look at Scheme, Racket, OCaml, and Standard ML.
- amelius 11y ago> threads should only be used to exercise multiple CPU cores and never as a way to work around blocking IO. 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.
- jcoffland 11y agoYou may be right that a lot of software has some CPU bounds parts but I would argue that most code is IO bound. Usually there is a only a small kernel in a program that actually does heavy computation and this is the only place you should use threading.
- Coding_Cat 11y agoWhat's wrong with threading on IO? For example if you have a webserver which has to wait on replies from various other resources while serving enough clients to saturate itself. 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.
- jacques_chester 11y ago> What's wrong with threading on IO? To modify JWZ's famous joke: You have a problem. You say, "I know, I'll use threads!" Nowyou prob h2ave lems
- mystikal 11y agohaha, also: Now y
- pjkundert 11y agoGreat advice, in general. One small point to remember is that it is impossible to implement a completely non-blocking output using the C++ ostream classes. 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.
- jcoffland 11y agoYou are right and I think this is a major flaw with the standard library.
- greydius 11y ago> threads should only be used to exercise multiple CPU cores and never as a way to work around blocking IO Never use threads in C++. Gotcha. Good thing I'm learning Rust, then.
- zoul 11y agoWhile I admire the amount of thinking that went and still goes into C++, for me the question is opposite: why ever C++? It seems to me that trying to improve a language by ecosystem or convention will always be worse than using a language already designed around what we have learned and what has changed since C++ was born. If somebody really needs to have the performace or be that close to the hardware, they can still probably find a better language today (Rust, Go?). But all others will certainly be better served by more modern, higher level languages. Just reading the examples in the PDF makes my head hurt.
- santaclaus 11y ago> they can still probably find a better language today Rust's ecosystem is still a bit anemic. I've played around with Rust, and I like the language, but C++ has a much wider array of battle-tested libraries at one's beck and call. Rust's development tools are also somewhat of a monoculture, at the moment.
- arnorhs 11y ago> Rust's development tools are also somewhat of a monoculture, at the moment. Care to elaborate? I'm curious
- jgh 11y agoFor us we support multiple platforms (win, osx, ios, android, ...) and need to interact with hardware io, codecs, and gpu apis. We could use C, I suppose, but we'd be giving up some of the niceties of C++11 such as smart pointers that make life much simpler. That's not to say we don't have some platform-specific code in the "preferred" language (in some cases there is no choice in the matter), but most of the system is C++.
- exprI 11y agoConsidering how much more resources programs use by the day, would you really like to run an OS written solely in, say, Python? Moore's law is coming to an end. It's only preferable that programmers use more efficient languages, even if happens at a mental cost. It's also more environmentally friendly.
- jacques_chester 11y agoSummarising how I usually seeing these discussions go: The usual argument goes that C++ is bad because of the problems of C. The counter-argument is that "nobody does that in modern C++". The counter-counter argument is that: 1. there's a lot more not-modern-C++ than there is modern C++. 2. there seem to be dozens of not-really-smoothly-interchangeable notions of what "modern C++" is, because the language is so vast, and there have in fact been several overlapping generations of "modern C++". 3. It still requires conscious and vigilant effort, over and above the baseline the language gives you, to not introduce game-over security or reliability flaws. The counter-counter-counter argument is that these are true of every language. Which, being not strictly and completely true in the particulars, is where the whole thing degenerates into personal reflections about $PET_LANGUAGE, hair-pulling, personal insults, blog posts about monads at twenty paces etc etc.
- MAGZine 11y ago> 2. there seem to be dozens of not-really-smoothly-interchangeable notions of what "modern C++" is, because the language is so vast, and there have in fact been several overlapping generations of "modern C++". Everyone I've talked to understands modern C++ to be C++11 or newer.
- titanomachy 11y agoC++11 adds to the language, but is there a strong consensus on what parts of pre-2011 C++ are not allowed in "Modern C++"? I have seen C++ code advertised as "modern" that still uses naked pointers, for example, while others claim that all pointers should be reference-counted. There is no agreed-upon algorithm that answers the question "is this source file written in valid Modern C++?", because there's no agreement on what that means.
- MAGZine 11y ago> 2. there seem to be dozens of not-really-smoothly-interchangeable notions of what "modern C++" is, because the language is so vast, and there have in fact been several overlapping generations of "modern C++". Everyone I've talked to understands modern C++ to be C++11 or newer.
- sehr 11y agocache http://webcache.googleusercontent.com/search?q=cache:http://lambda-the-ultimate.org/node/5313 http://webcache.googleusercontent.com/search?q=cache:http://...
- quchen 11y agoCached version: http://webcache.googleusercontent.com/search?q=cache:UB-yaeW3LgcJ:lambda-the-ultimate.org/node/5313+&cd=1&hl=en&ct=clnk&gl=de http://webcache.googleusercontent.com/search?q=cache:UB-yaeW...
- pmarreck 11y agoC++ is still plenty viable, but if you like avoiding bugs, John Carmack seems to have come to the conclusion that using a functional style (which is not exactly encouraged by C++) is advantageous: http://gamasutra.com/view/news/169296/Indepth_Functional_programming_in_C.php http://gamasutra.com/view/news/169296/Indepth_Functional_pro... "My pragmatic summary: A large fraction of the flaws in software development are due to programmers not fully understanding all the possible states their code may execute in. In a multithreaded environment, the lack of understanding and the resulting problems are greatly amplified, almost to the point of panic if you are paying attention. Programming in a functional style makes the state presented to your code explicit, which makes it much easier to reason about, and, in a completely pure system, makes thread race conditions impossible. "No matter what language you work in, programming in a functional style provides benefits. You should do it whenever it is convenient, and you should think hard about the decision when it isn't convenient."
- timwaagh 11y agoI clicked the title and it provided a great answer. something about mysql not connecting. i thought it answered the question until i googled it. a better title would be 'why not php'.
- cyber1 11y agoBecause we have Rust!
- Gratsby 11y agoLOL... why not PHP.
- jokoon 11y agoThe only thing that has always been behind, and might still be for a couple of years, is the include system, which causes huge delays when compiling and linking, even when editing one single file. When I make edits and hit build, the old C include system kicks in and it's a very long process. I'm using C++ but precompiled headers are not a standard (many details will prevent you to use them) and there are not decent ways to reduce build time to bearable ranges. I'm sure this is the main point that makes C++ so unattractive. If you're a programmer, having shorter code-write/build/test/repeat cycles is important if you don't want to lose focus on what you're doing. I don't know if build delays are specific to C++ or specific to microsoft, but if modules were available in some beta form I would try them ASAP. Even platform specific techniques would interest me... So yes, I'll love C++, but not only the ABI and build configs are not easily solved by CMake, but build times will never make C++ attractive enough. It's not not realistic to pretend you can be really productive with C++.
- santaclaus 11y agoModules were just put into a TS so hopefully we'll get them in C++19. I would love to have them now, however.
- justinsaccount 11y agoI had this to say about c++/go recently: Working on a c++ project: I feel stupid... and nothing works. Working on a golang project: go is stupid... but everything works. My issue with c++ is someone needs to write a "c++: the good parts" I may end up with rust, but right now I look at the documentation and some rust code and it's a bit overwhelming. Go may be stupid in a lot of ways, but for the most part it's pretty obvious how to accomplish something.
- philbo 11y agoIt's not exactly the same, but the closest thing to a "C++: The Good Parts" is Scott Meyers' "Effective C++", imho.
- bloodorange 11y agoUnfortunately, there are no updated versions of his books for C++14 or 17. I owe a lot to the books though.
- santaclaus 11y agoEffective Modern C++ covers C++14, and specifically points out where it differs from C++11 (I'm thinking about the discussion of decltype, here).
- lmedinas 11y agoTrust me even though it's not updated everything he mentions in the book is still valid. If you want to really know more about specifically modern C++ there is always Modern Effective C++
- saboot 11y agoThe C++ standards committee has started a guidelines document which encompasses the latest features of C++11/14 https://github.com/isocpp/CppCoreGuidelines https://github.com/isocpp/CppCoreGuidelines
- 11y ago
- dman 11y agoSite is down so I cant comment on content from the article. As a working programmer here are some things that I consider to be C++ virtues a. Control over memory layout b. Control over allocation policies c. Deterministic deallocation of objects on scope exit d. Generics and specialization of generics I am always mystified how many languages miss out on item a.