Does std::endl fix your multithreaded prints? (C++)

Поделиться
HTML-код
  • Опубликовано: 29 сен 2024

Комментарии • 184

  • @crobes4155
    @crobes4155 2 года назад +38

    If each of the core guidelines had a video like this with you explaining them I'm sure C++ would be a lot easier for a lot of people :) Thanks for the in depth explanation and the consideration of different C++ standards for the code examples! #clion

  • @fennecbesixdouze1794
    @fennecbesixdouze1794 2 года назад +59

    I like to use the following rule of thumb for deciding when to flush the buffer: if it's yellow, let it mellow, if it's brown, flush it down.

  • @333deejay333
    @333deejay333 2 года назад +2

    Now I should tell my teacher to correct his “Introduction to C++” manual ;). #clion

    • @mCoding
      @mCoding  2 года назад +3

      Well, for a teacher I can understand that what you teach your students doesn't necessarily focus on best practices. Sometimes it's not worth it to explain a best practice if the benefit is not core to the lesson and would take a lot of time. Hopefully your teacher is already on board, or feel free to send them this video :)

  • @arnemue5606
    @arnemue5606 2 года назад +3

    Just starting with C++ and really like to watch these videos to get some deeper understanding. Thanks a lot #clion

  • @petrostzathas8766
    @petrostzathas8766 2 года назад

    It's nice that you have expanded your topics to include c++ #clion

  • @marcnassif2822
    @marcnassif2822 2 года назад +2

    Love it! C++ really isn't as hard as people made it out to be when I first started, and videos like this really help me getting more and more into programming
    #clion

  • @yolosaurusrex90
    @yolosaurusrex90 2 года назад

    i don't even write C++ (more of a kotlin/java and python guy) but i appreciate these videos anyway. thanks for randomly choosing me to have #clion by the way, really appreciate it

  • @CAMOBAP795
    @CAMOBAP795 2 года назад

    Awesome video as always!
    07:21
    1. a batch writing (every 1000 lines) is a risk to loose a batch
    2. isn't synchronized queue will do the same with a mutex under the hood?

    • @mCoding
      @mCoding  2 года назад

      Thanks!
      1. Potentially yes, more in the situation of a long lived process that writes infrequently. Handling failed writes is a much more complex topic that has a few decent solutions depending on the situation. Although, a common theme of the solutions is actually point 2!
      2. Yes under the hood there will still need to be synchronization, but this centralizes the place where writing happens, making it easier to attempt to handle things like failed writes. It is more of an organizational construct to help keep your architecture clean.

  • @codewithjc4617
    @codewithjc4617 2 года назад

    Nice video, quite interesting.

  • @PauL-jv7rg
    @PauL-jv7rg 2 года назад

    #clion could be a nice tool to learn C++

  • @MertTheDragonReborn
    @MertTheDragonReborn 2 года назад

    I did not know that endl was a bad practice. Thanks! #clion

    • @mCoding
      @mCoding  2 года назад +1

      So lucky! You get a CLion! Email me to claim (find on my about me).

    • @MertTheDragonReborn
      @MertTheDragonReborn 2 года назад

      @@mCoding 18 is the answer. Best regards Mert.

  • @tyronewilson6463
    @tyronewilson6463 2 года назад

    I recently worked on some distributed computing code in which I found out this myth was totally false, thankfully it only really needed to return data at the end of the process. So I flushed all the debug and printing info into a string stream printed them from the managing thread. #clion

  • @gregorymorse8423
    @gregorymorse8423 Год назад

    I believe std::endl should portably allow Windows carriage return line feed pattern. Also auto flush on newline is a common feature of various buffered OS objects like stdout or stderr. Therefore flushing is sometimes automatic and unavoidable. As for thread safety of the OS write and read calls, likely they are thread safe. So all the C++ nonsense here though useful is far from the only perspective on the issue. He left out the C and raw OS library perspective.

    • @mCoding
      @mCoding  Год назад +1

      std::endl does not produce a carriage return on Windows. It produces a newline then flushes on all platforms, as required by the standard. While auto flush on newline may happen for certain stream, it does not happen for all of them, especially not file or string streams, and in these cases endl is often a common and significant performance slowdown. The advice to avoid endl is not my personal vendetta, it is time tested battle proven advice even recommended in the C++ core guidelines maintained by Bjarne, creator of C++: isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rio-endl. I don't talk about C in this video because this is a C++ video about a specific misconception about std::endl, not a how to guide for printing across different languages. C is a different language than C++ and it does not have std::endl.

    • @gregorymorse8423
      @gregorymorse8423 Год назад

      @mCoding in Java the System.LineSeparator does give a OS specific newline. Didnt know C++ standardized the Linux variant. Interesting reference thanks! Indeed the lower level stuff is another topic. But one which although you understand, many don't.

  • @michaelflynn6952
    @michaelflynn6952 2 года назад

    Great stuff #Clion

  • @t0prar
    @t0prar 2 года назад

    Nice explanation
    #clion

  • @nabeelsherazi8860
    @nabeelsherazi8860 2 года назад

    Neat stuff #clion

  • @bman12three43
    @bman12three43 2 года назад

    cool video #clion

  • @ahmehhhd
    @ahmehhhd Год назад

    #clion

  • @Paulmall3
    @Paulmall3 2 года назад +20

    Even when I have scoped lock available, I prefer lock guard for when you are only locking exactly one mutex. I feel it shows clearer intent, and also you get a compiler error if you forget to give it the mutex. You don't get that with scoped lock as no mutex is a valid initialisation. Would love to know if there are any downsides to this approach. #clion

    • @mCoding
      @mCoding  2 года назад +12

      Eventually, I hope tooling like clang-tidy would warn on explicit zero-argument scoped_lock, but for now I think it's perfectly reasonable to continue using lock_guard to avoid this potential (and reasonable) human error.

  • @mustafasuve3109
    @mustafasuve3109 2 года назад

    #clion

  • @tsukiiiiiii
    @tsukiiiiiii 2 года назад +3

    RUclips gang

  • @jharmer95
    @jharmer95 2 года назад +6

    Manual flushing expresses intent much better than endl anyway. Sometimes you want to flush (ex. when you're writing a logger or test where the app could terminate after the write but before the stream is destroyed/auto-flushed). Thanks for the video ☺️ #clion

  • @ccnesbitt
    @ccnesbitt 2 года назад +10

    Been really enjoying your videos, especially your recent dive into an assortment of C++ topics. I ended up purchasing the book Effective Modern C++ because of your video outlining nooby C++ habits, most of which were applicable to my traditional "C style"
    approach to programming in C++.
    About a quarter of the way through the book, and learning a bunch. Thanks!
    #clion

    • @mCoding
      @mCoding  2 года назад +2

      Awesome, great initiative and best of luck with your reading! Feel free to join the discord and ask questions any time :)

  • @siddharth-gandhi
    @siddharth-gandhi 2 года назад +8

    I don't think I've ever seen better and more concise videos on CPP and Python topics anywhere else, so bravo for that! #clion

    • @mCoding
      @mCoding  2 года назад +1

      Many thanks, I'm glad you enjoy!

  • @Possseidon
    @Possseidon 2 года назад +17

    By default std::cout is thread-safe, in that a single call to operator

    • @mCoding
      @mCoding  2 года назад +1

      Yes this is good to keep in mind. Funnily enough, the core guideline right before "avoid endl" is "SL.io.10: Unless you use printf-family functions call ios_base::sync_with_stdio(false)" ( isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#slio10-unless-you-use-printf-family-functions-call-ios_basesync_with_stdiofalse ). So it is actually recommended to give up the atomicity of std::cout for performance reasons. But, if you are aware of the atomicity guarantee and are mindfully depending on it, then I wouldn't necessarily be opposed. Thanks for mentioning!

    • @rajburtonpatel6702
      @rajburtonpatel6702 2 года назад

      @L. Kärkkäinen why use std::flush in combination with the single writes?

    • @Possseidon
      @Possseidon 2 года назад

      @L. Kärkkäinen Funny enough, for this exact reason std::cerr flushes *everything* immediately, so you effectively still don't need any flush/endl at all. For regular logging use std::clog which also prints to stderr but does not flush automatically.

  • @pavlosspanoudakis1585
    @pavlosspanoudakis1585 2 года назад +1

    Being fluent with C++98, post C++11 code looks exotic to me #clion

  • @christopherweeks89
    @christopherweeks89 2 года назад +2

    In most c++ implementations, streams are already thread safe. The reason this example creates garbage output is because of how the output is generated with multiple calls to operator

    • @mCoding
      @mCoding  2 года назад +2

      True! cout, cin, etc... are required by the standard to be thread-safe (unless sync_with_stdio(false) is used), and most implementations implement file streams in a thread-safe way, even though thread-safety is only a requirement (by the standard) for cout, cin, etc... but not file streams, so indeed a local stringstream is a decent solution. For user-defined ostreams, of course all bets are off with this approach, and I bet that stringstream itself is not thread-safe (case when ostream passed is a stringstream) , so I would still recommend one of the methods in the video for that reason. I would also say that if you are using C++20 and taking the osyncstream approach, the code looks very similar to your stringstream approach and doesn't require the os

  • @ChandrapalSd
    @ChandrapalSd 2 года назад +1

    Do you have any plan of making videos on opengl or similar topics ? #clion

  • @jamesmacak7898
    @jamesmacak7898 2 года назад +1

    I'll add my two cents. #clion

  • @nathanoy_
    @nathanoy_ 2 года назад +1

    your videos have absolute priority. ill stop whatever i do when a video of yours pops up. #clion

    • @mCoding
      @mCoding  2 года назад +1

      Great to hear! Thanks so much for your support!

  • @Roter_Wolf
    @Roter_Wolf 2 года назад

    What's the syntax with the curly braces called? Like in `std::ofstream file{"out.txt"}` what are the curly braces doing? I'm somewhat used to c++ through Qt, but I don't think I've seen this syntax before

  • @leviathan7477
    @leviathan7477 2 года назад

    So I'm curious, what is std::endl used for then? I'm not too familiar with C++, but I always just assumed it was a way to get the system dependent line separator (containing a carriage return on some systems). If there's no legitimate use for it, can it be deprecated?? #clion

  • @Санек-т1р
    @Санек-т1р 2 года назад

    Cool informative video, don't know that endl kill productivity. Thanks #clion and mCoding

  • @danielrhouck
    @danielrhouck 2 года назад

    I wasn’t sure if it could help or not, because I didn’t know if some of the relevant buffers were thread-local, but I knew enough to not trust it completely.
    Also I’ve wanted to try #clion for a while.

  • @RGAM1989
    @RGAM1989 2 года назад +1

    I was wondering why everyone added #clion in their comments, and then I read the description of the video...
    I saw where that myth was comming, but I enjoyed all the video from start to end.
    As someone who used C++ heavily when C++11 was still a new thing, I was curious to know how is the standard about multithreading today.
    Thank you for your content, mCoding!

  • @davea136
    @davea136 Год назад

    "Side effets are bad."
    Everything added to the standar since 2000 has a host of side effects.
    Jesus take the wheel.

  • @Songfugel
    @Songfugel 2 года назад

    Such a difference in C++ 20 implementations robustness #clion

  • @arashfatehi9971
    @arashfatehi9971 2 года назад

    Giving solution for different C++ version was superb, thanks for the great video #clion

  • @xialemai6412
    @xialemai6412 2 года назад

    My idea as I was watching was to make a string with the line including the
    , then

  • @tatianaes3354
    @tatianaes3354 Год назад

    What about the legendary classics like C++08?

  • @rajburtonpatel6702
    @rajburtonpatel6702 2 года назад +10

    this was great! as a TA for a data structures course, I've always taught the use of std::endl; knowing it flushes the buffer but not considering the impact on large-scale performance. I'll make sure to integrate use of
    now. The multithreading examples were fascinating. thank you! #clion

  • @ltstaffel5323
    @ltstaffel5323 2 года назад

    Awesome content! Also really cool to see Jetbrains do a giveaway, especially for #clion

  • @MrD0r1an
    @MrD0r1an 2 года назад

    Didn't know about jthread in c++20. #clion

  • @xdoof4061
    @xdoof4061 2 года назад +1

    What ide and theme are you using?

    • @mCoding
      @mCoding  2 года назад

      Clion and Monokai Pro!

  • @harier64
    @harier64 2 года назад

    Awesome, would be nice to see more videos about multithreaded code in c++. #clion

  • @sanduchicu7545
    @sanduchicu7545 2 года назад

    i hate visual studio code cuz it sometimes doesn't compile changes i make #clion

  • @john.dough.
    @john.dough. 2 года назад +1

    This was great! There are a lot of people who make very basic or very advanced programming videos, but you are amazing at intermediate level content.
    Keep up the great work.

  • @arshadjaveed7877
    @arshadjaveed7877 Год назад +1

    Amazed by your videos

  • @niikurasu2855
    @niikurasu2855 2 года назад +1

    Hey James! Im currently a high school senior and very advanced in Python. I would like to learn C++ but don't really know where to start. I know the basics (pretty much C) but modern C++ is a little too much for once. Do you know a great ressource where I can learn it?

    • @PugMaxer
      @PugMaxer 2 года назад

      Hi there! I would reccomend finding an online free pdf of "The c++ programming language" by barne stroustrup. You should be able to get one for c++11 free online, don't forget earlier then c++11.

  • @darvil82
    @darvil82 2 года назад

    C++ scares me, but I guess I could give it a try if I get #clion 😳

  • @BoyNextDoor1729
    @BoyNextDoor1729 2 года назад

    It would be nice to know: is there any scenario where endl is needed or preferred? #clion

  • @Lojdika
    @Lojdika Год назад

    I really appreciate the "thanks
    " cout

  • @sohangchopra6478
    @sohangchopra6478 Год назад

    Nice Video! Definitely need to re-watch 🙂

  • @РоманМитасов-ь2о
    @РоманМитасов-ь2о 2 года назад

    Ok then. Why we have std::endl in C++, if it's usage is discouraged? Isn't that weird that at the first glance simple end-of-line constant turned out to be flushing operation? What's the original purpose in that? #clion

    • @mCoding
      @mCoding  2 года назад +1

      As is the case with many things in C++, it was chosen long long ago before the implications were fully understood and at a time where the constraints of the hardware were very different from what they are today. And, for backwards compatibility, it cannot be changed, ever.

  • @raz0229
    @raz0229 8 месяцев назад

    Are we still on it? #clion

  • @frans.8906
    @frans.8906 2 года назад

    And I remember the professor that teached me C++ say to always use std::endl because "it's the c++ way"... #clion

    • @mCoding
      @mCoding  2 года назад +1

      Teaching is hard, sometimes professors say things that are good approximations for learners or are otherwise helpful simplications for the classroom allowing them to skip longer explanations and allow the class to spend precious time on more important topics. Since the biggest difference is worse performance using endl, I can understand that a beginner class (the kind where you would be learning what endl is) would not be concerned much with performance, so it would be simpler to just tell you to use endl and move on.

  • @packetpunter
    @packetpunter 2 года назад +1

    Thanks for your stellar videos. Home sick bc the holidays, and your videos are helpful both in coding and helping me get passed my rut. Thanks again.
    Also, #clion

    • @mCoding
      @mCoding  2 года назад +1

      Get well soon!

  • @notjoss
    @notjoss 2 года назад

    My solution to this is const std::string endl="
    "; at the start of my program and pretend to use std::endl to confuse everyone. #clion

    • @mCoding
      @mCoding  2 года назад +1

      Chaotic good, I see.

  • @jedynywiking
    @jedynywiking 2 года назад

    This brings some great memories, i moved away from c++ (yes yes, heresy) but every time I see your videos it makes me want to get back :) #clion for the win :D

    • @mCoding
      @mCoding  2 года назад

      Use whichever language is most useful for whatever you are working on. I have no ill feelings of other languages.

  • @andreichirap3259
    @andreichirap3259 2 года назад

    #clion once again a grait video, thx :)

  • @whamer100
    @whamer100 2 года назад

    i wish i knew about ossyncstream earlier, actually super helpful

    • @mCoding
      @mCoding  2 года назад +1

      Glad i could help!

  • @weeb3277
    @weeb3277 2 года назад +1

    #cnile

    • @mCoding
      @mCoding  2 года назад

      My script checks if "#clion" in comment.lower(), so you'll miss out if this is your only comment!

  • @fejfo6559
    @fejfo6559 2 года назад

    Could you fix the problem by first creating the line you want to print as a string and only doing one

    • @mCoding
      @mCoding  2 года назад

      Indeed, std::cout has special wording in the standard that actually guarantees that this would work, see en.cppreference.com/w/cpp/io/cout for a brief explanation. Of course, if you are writing to a file you're out of luck!

  • @jadek9_
    @jadek9_ 2 года назад

    Mechatronics ftw #clion

  • @anselmschueler
    @anselmschueler 2 года назад

    hmm interesting thanks #clion

  • @garrysingh4484
    @garrysingh4484 2 года назад

    What Code Editor & Theme Are You Using ???

    • @mCoding
      @mCoding  2 года назад

      CLion and Molokai Pro theme

  • @AMith-lv2cv
    @AMith-lv2cv 2 года назад

    what color scheme is this?

  • @MithicSpirit
    @MithicSpirit 2 года назад +1

    0:26 wouldn't the compiler be able to optimize that second call out? #clion

    • @fennecbesixdouze1794
      @fennecbesixdouze1794 2 года назад

      Two writes is different observable behavior than one write, so no, not if your compiler is correct.

    • @tsunekakou1275
      @tsunekakou1275 2 года назад

      probably not, would be weird to concat two string literals into one.

    • @mCoding
      @mCoding  2 года назад

      There is a potential the compiler could avoid the machinery of calling a function (although neither clang nor gcc does in this case, see godbolt.org/z/cqEnP1Whs ), however, the compiler cannot optimize away a flush due to it's nature of causing a side-effect.

  • @DebashishGhoshOfficial
    @DebashishGhoshOfficial 2 года назад

    Can't we use std::format in C++20? #CLion

    • @mCoding
      @mCoding  2 года назад

      Yes! But I'm itching for better compiler support before recommending it yet. I will make a video about it once the major compilers all have it working in a stable version that most of my viewers would be able to upgrade to easily.

  • @arjunaudupi7956
    @arjunaudupi7956 2 года назад

    #clion the new lion in town

  • @its_code
    @its_code 2 года назад

    Amazing 😍😄 love 💕 from Pakistan

  • @luisclaudiobritobatista5332
    @luisclaudiobritobatista5332 2 года назад

    Great video! #clion

  • @rujixie9025
    @rujixie9025 2 месяца назад

    gold!

  • @MrTechnoholding
    @MrTechnoholding 2 года назад

    Great video #clion

  • @AdmiralCaner
    @AdmiralCaner 2 года назад

    Thank you for adding previous C++ Version. I'd like to see more 'Myths' #clion

  • @TheAkatran
    @TheAkatran 2 года назад

    #clion is enough?

  • @why917
    @why917 2 года назад

    Nice video! #clion

  • @artemetra3262
    @artemetra3262 2 года назад

    great video! i'm very very new to multithreading and threads overall and this video was very helpful, thanks :D #clion

  • @Benjo1102
    @Benjo1102 2 года назад

    #clion I use vs code

  • @philipsuskin6843
    @philipsuskin6843 2 года назад

    Great video. Honestly didn’t even know the C++11 solution was that compact! #clion

  • @demonidraigon
    @demonidraigon 2 года назад

    Great video, really informative and useful, i might not have understood 1/2 of the things you said, but someday tomorrow i will!
    #clion

  • @JohnZakaria
    @JohnZakaria 2 года назад

    I liked the different C++ version comparisons.
    I am using C++ 17 and only used lock guards because I didn't know better
    #clion

  • @CallumPooleProgrammer
    @CallumPooleProgrammer 2 года назад

    Cool video #clion

  • @darer13
    @darer13 2 года назад

    thanks for your videos. do you think you could do some videos on programming enviroments? text editor + compiler + debugger + build system + meta build system? #clion

  • @ephrxauth7977
    @ephrxauth7977 2 года назад

    Thanks for explaining
    and std::endl in depth, it was indeed virtually impossible to find an explanation I’d understand/believe until now.
    I’d also love to use #clion on my Mac. I’m not into text editors for C++ in MacOS.

  • @eliasleb
    @eliasleb 2 года назад

    Excellent #clion

  • @kornel001026
    @kornel001026 2 года назад

    #clion helpful vid

  • @masheroz
    @masheroz 2 года назад

    I've only begun to dabble in c++, but am learning lots from your channel, including python. #clion

  • @daniihh
    @daniihh 2 года назад

    #clion

  • @komornikja6211
    @komornikja6211 2 года назад

    bazinga #clion

  • @polpop4509
    @polpop4509 2 года назад

    #clion noicee!

  • @ThatCowThatGoesMoo
    @ThatCowThatGoesMoo 2 года назад +1

    I love your channel, even if something I watch never impacts my life I just love the in-depth explanations you give for everything #clion

    • @mCoding
      @mCoding  2 года назад +1

      Thanks so much! Glad you enjoy!

    • @mCoding
      @mCoding  2 года назад

      Hope this reply gets to you! You get a CLion! Email me to claim (find on my about me).

  • @XxyehezkelxX
    @XxyehezkelxX 2 года назад

    Amazing vid man! That syncstream is awesome, I can never keep up with the new features.

  • @cazzxd3346
    @cazzxd3346 2 года назад

    Epic #clion

  • @ВикторКуликов-х3б
    @ВикторКуликов-х3б 2 года назад

    nice #clion

  • @alice-smith
    @alice-smith 2 года назад

    Cool #clion

  • @NaN-se8ye
    @NaN-se8ye 2 года назад

    Already knew that but still, the delivery of your content is great! #clion

  • @ivanlee1
    @ivanlee1 2 года назад

    I always liked c++ since it was my first programming language but I did not go deep with it. Your videos are really helpful for me to learn more. #clion

  • @justinliu7788
    @justinliu7788 2 года назад

    #clion

  • @laurenwrubleski7204
    @laurenwrubleski7204 2 года назад

    Great stuff as always! As a primarily C developer, I always enjoy learning about the features in C++ that I should be using but never know about, keep up the good work! #clion