Threads in C++

Sdílet
Vložit
  • čas přidán 9. 06. 2024
  • Patreon ► / thecherno
    Twitter ► / thecherno
    Instagram ► / thecherno
    Discord ► thecherno.com/discord
    Series Playlist ► thecherno.com/cpp
    Thank you to the following Patreon supporters:
    - Dominic Pace
    - Kevin Gregory Agwaze
    - Sébastien Bervoets
    - Tobias Humig
    - Peter Siegmund
    - Kerem Demirer
    Gear I use:
    -----------------
    BEST laptop for programming! ► geni.us/pakTES
    My FAVOURITE keyboard for programming! ► geni.us/zNhB
    FAVOURITE monitors for programming! ► geni.us/Ig6KBq
    MAIN Camera ► geni.us/t6xyDRO
    MAIN Lens ► geni.us/xGoDWT
    Second Camera ► geni.us/CYUQ
    Microphone ► geni.us/wqO6g7K

Komentáře • 397

  • @TheCherno
    @TheCherno  Před 6 lety +208

    Hey guys, looks like CZcams is still processing this video (#classic), so hopefully it will be in HD soon. Thanks for watching :)

    • @SkillMinecrsft
      @SkillMinecrsft Před 6 lety +14

      Could you also make a video on mutexes and atomic variables. I am mainly confused about who should own the mutex in an OOP scenario...

    • @altermetax
      @altermetax Před 6 lety

      PlutoYT: if you had just called the function, you wouldn't be able to wait for user input to terminate the loop. The best you could do is ask at each iteration of the loop whether to continue.

    • @2605mac
      @2605mac Před 4 lety

      Thank your for all your effort. With your videos I'm starting to understand much more things in c++. Greetings from Poland!

    • @mayankmaurya8631
      @mayankmaurya8631 Před 4 lety +1

      Why your int main() not returning anything? Shouldn't that cause error?

    • @2605mac
      @2605mac Před 4 lety

      in c++, if you dont write return 0; at the end of main function, it presums that ends with that.

  • @PaprikaX33
    @PaprikaX33 Před 6 lety +1649

    Explaining thread in the woods because another cherno::thread is using the house for another video

  • @yee3135
    @yee3135 Před 6 lety +764

    Walked in the woods, found a
    Cherno doing c++ multithreading.

  • @bulentgercek
    @bulentgercek Před 4 lety +125

    Cherno gave us a simple and great example of how to display a looping "Loading" text animation while waiting for our models and other materials to load. We learn c ++ with practical examples. Great things for beginners. Thanks dude!

    • @vadiks20032
      @vadiks20032 Před 2 lety +14

      everyone's gonna be surprised they can exit their loading screen by pressing enter! genious game design!

  • @shanmukhpatel
    @shanmukhpatel Před 4 lety +20

    There are plenty of good C++ tutorials out there, and this is by far the best C++ channel. Thank you.

  • @mohnish.deshpande
    @mohnish.deshpande Před 10 měsíci +6

    Cheers to Cherno! Hands down the best C++ tutorials. My guy somehow manages to explain a relatively complex topic along with example in about 10 mins. Just Awesome.

  • @danielsimionescu298
    @danielsimionescu298 Před 5 lety +65

    I miss these videos in nature 😢

  • @whynot-vq2ly
    @whynot-vq2ly Před 5 lety +63

    I bet there was a bear family just behind you hiding in the bushes and learning C++:D
    great tutorial thanks a lot

  • @alicelikkol1326
    @alicelikkol1326 Před 4 lety

    You're doing great job bro. You are explaining things in a really clear way and not doing it in a boring way. Lucky to find you

  • @kartikpodugu
    @kartikpodugu Před rokem +1

    Thanks for the C++ tutorials. I have seen most of your videos multiple times over the last few years.
    Now, your videos are my reference content whenever I need something in C++

  • @nirmalkumarsingh7589
    @nirmalkumarsingh7589 Před 2 lety +2

    You are great at making things interesting. Loved all your videos so far. Thank you.

  • @dkd0m23
    @dkd0m23 Před 6 lety +1

    Thx for this series, exactly what i needed right now ! :)

  • @EugeneSorokacorp
    @EugeneSorokacorp Před 5 lety +11

    Dude I LOVE that you are in the woods. I want my office as programmer and engineer to be the summit of some mountain or in the middle of the forest. Thats badass.

    • @Mystixor
      @Mystixor Před 3 lety

      Immediately reminds me of Ex Machina!

  • @nilaysharma4040
    @nilaysharma4040 Před 6 lety +4

    I have been waiting for this for so long...

  • @dominikvereno8404
    @dominikvereno8404 Před 6 lety +1

    Thank you for the clear tutorial! Very easy to follow your explanations

  • @moritz5102
    @moritz5102 Před 6 lety +1

    I really like your videos. Great knowledge and charisma!

  • @tkaotic
    @tkaotic Před 4 lety +5

    Love how you explained this. Ended up watching your video instead of my instructors' lecture because it was more content in less time more completely explained. Thanks for what you do!

  • @wes443
    @wes443 Před 6 lety +9

    A video on exception handling and a video on callbacks would be awesome if you haven't done those topics yet! Awesome videos man, you are a great teacher.

  • @AlFasGD
    @AlFasGD Před 4 lety +14

    Came here because of the recommendation, stayed to see how C++ enables threading, learned that C++ offers custom literals

  • @WillMcCKill
    @WillMcCKill Před 6 lety +5

    Brilliant production Cherno! Both informative and aesthetically pleasing. I'm really looking forward to the new game engine series.

  • @snowyalbino130
    @snowyalbino130 Před 4 lety

    This series is absolutely outstanding!

  • @midnqp
    @midnqp Před 10 měsíci +1

    Unique ideas to appear cool in CZcams! It sure is working.

  • @adamrushford
    @adamrushford Před rokem

    Every Time I have a problem just you clarifying it gets me going!

  • @michaplucinski142
    @michaplucinski142 Před rokem

    that's something I was thinking about some time ago, great think and great video

  • @neiltsakatsa
    @neiltsakatsa Před 6 lety +94

    My wish is that maybe one day teach us about Neural Networks in C++. I'm loving your C++ series man !

    • @CrunchPlaysGames
      @CrunchPlaysGames Před 6 lety +27

      Alex Tol, van If you want to get into neural networks, C++ doesn't have as many libraries and options compared to a highly supported language like Python.

    • @neiltsakatsa
      @neiltsakatsa Před 6 lety +10

      It's difficult implementing neural networks in C++ I agree, but if it is fast and efficient plus it gives you more control.

    • @SkillMinecrsft
      @SkillMinecrsft Před 6 lety +10

      Not too difficult I can send u some code of a simple one if u want...

    • @CrunchPlaysGames
      @CrunchPlaysGames Před 6 lety +5

      Neil Tsakatsa I agree C++ has major performance benefits, but in my opinion, C++ isn't the best in terms of helping beginners.

    • @UncoveredTruths
      @UncoveredTruths Před 6 lety

      just use (py)/torch if you want fast GPU accelerated networks, else if you are CPU bound use Caffe

  • @itsharsh5997
    @itsharsh5997 Před 5 měsíci

    That is so cool!!! like this multi-threading stuff is so freaking cool

  • @icosanalysis
    @icosanalysis Před 6 lety +3

    Hey Cherno - Amazing series. I would be very interested in a couple that explore optimisation strategies in greater detail.

  • @Bozemoto
    @Bozemoto Před 6 lety +7

    I was teaching myself some network programming using UDP sockets and was printing off the state of the server into the console. Problem is that std::cout is really slow and it was taking up so much time my server was lagging behind the game. So what I did was stick the std::cout into a thread of it's own and put it in an infinite loop and just sleep it for 0.2 seconds after every draw. Just a toy example but something simple that shows the usefulness of threads.

  • @mohammedmedhat3077
    @mohammedmedhat3077 Před 6 lety +5

    OMG i have been waiting

  • @TheBusttheboss
    @TheBusttheboss Před 2 měsíci

    Love your introductions.

  • @ashutosh108
    @ashutosh108 Před 6 lety +62

    Note: in real applications one should always use e.g. std::atomic for s_Finished (or other ways to ensure thread safety) to avoid race condition, which is a kind of undefined behaviour, which is very bad.

    • @viktorstrate
      @viktorstrate Před 6 lety +2

      Is this necessary when you are only writing to it from one thread?

    • @robertenyedi5692
      @robertenyedi5692 Před 6 lety +18

      This example is completely thread safe for 2 reasons:
      1. Because he only modifies the value of the flag on the main thread so other threads could read its value without any problem. (2 thread cannot modify a variable value at the same time, that would cause a nice crash).
      2. Boolean value is stored on a signle bit (0 = false, 1 = true), that means if the main thread changes its value at the same time the side thread read its value, it would be 0 or 1 anyway (so if its 0 the next time he checks it it gonna be 1 anyway). This is not true with real numbers where this technique can lead you to data corruption.
      In engines such as UE4 and others this technique is used heavly, because you don't waste any time on setting up mutexes and checking its locks, etc...

    • @ashutosh108
      @ashutosh108 Před 6 lety +8

      The code from the video "kind of works" which means it definitely works on x86 in most popular current compilers (but might break due to boolean check elimination if you enable optimization ), but is not guaranteed to work on other platforms or even future compilers because it exhibits undefined behaviour according to C++ memory model. Boolean writes (and int writes) are atomic on x86, but, say, int writes are not atomic to non-aligned addresses on ARM. I believe even bool writes might be thread-unsafe on some platforms due to memory barriers (one core sees "false", another sees "true").
      Now, if you only write for x86 and did check that all current processors/compilers accept it, and have commented it heavily to avoid future bugs by non-suspecting future programmers, then maybe it's OK to write such code. But I think in that case one should know that they are breaking the rules of C++ memory model: one should assess the risks/rewards for their particular situation, whatever UE4 and others do.

    • @robertenyedi5692
      @robertenyedi5692 Před 6 lety +2

      That is true, my explanation is only limited to the x86 platform. Before you do any kind of threading, the first thing what you have to do is checking if the current platform the application is running on is atomic or not. I'm not saying that you should always avoid mutexes, but on boolean flags usually you can (depends how the system is designed). Note that mutexes are not for free (it costs more memory and CPU checks) and settings up mutexes on every (lets say 1000) booleans it could impact the performance.

    • @DeShark88
      @DeShark88 Před 2 lety +2

      @@robertenyedi5692 "Boolean value is stored on a signle bit (0 = false, 1 = true)" Bools aren't stored as a single bit (or even byte necessarily), and that's not relevant anyway. As ashutosh108 points out, the issue is with atomicity. Point 1 is valid though I think, probably... most of the time.

  • @Maria-nu5yo
    @Maria-nu5yo Před 4 lety

    This was so helpful--thank you!

  • @edenr1988
    @edenr1988 Před 6 lety

    well explained, thanks for this awesome tutorial!

  • @pwrdwnsys
    @pwrdwnsys Před 6 lety

    Thanks for another awesome video!

  • @user-bl4mm5pr9g
    @user-bl4mm5pr9g Před 6 lety

    Thank you alot for your videos!

  • @HonsHon
    @HonsHon Před 4 lety

    That was a really nice review! Thank you

  • @zawarudo1818
    @zawarudo1818 Před 2 lety

    i cant thank you enough, finally found what i needed

  • @DestroManiak
    @DestroManiak Před 3 lety

    This is really good explanation for this.

  • @matebelenyesi3092
    @matebelenyesi3092 Před 3 lety +9

    Awesome video!
    Can you do please videos about multithreading problems and how to avoid them? (data race, deadlock,livelock,starvation, etc.)

  • @techguru7176
    @techguru7176 Před 3 lety

    Great video, love wood scenery

  • @zfighter3
    @zfighter3 Před 6 lety

    Great vid as always

  • @padaladileep5906
    @padaladileep5906 Před 4 lety +1

    Locations behind looks so peaceful

  • @abdfrehat2640
    @abdfrehat2640 Před 2 lety

    Thanks Cherno

  • @mansioncapital3358
    @mansioncapital3358 Před 4 lety

    great tutorial!!! I love your videos

  • @till-213
    @till-213 Před rokem +1

    Note that simple thread example is actually wrong: it accesses a global variable (s_Finished) from two different threads without using proper thread synchronisation - which according to the C++ 11 standard is "undefined behaviour".
    In fact, a C++ compiler is explicitly allowed to "optimise away" the read- access to the global variable s_Finsihed in your worker thread. Why? Because access to that variable is not using any thread synchronisation mechanisms (such as e.g. std::atomic), so the compiler is able to say: "Hey, s_Finished is never changed to false in this function call, so I may as well replace it with while(true)!". Of course also depending on the "optimisation level" that you set during compilation.
    And you would end up with a worker thread that would never stop!
    Also e.g. refer to the excellent CZcams video "Back to Basics: Concurrency - Arthur O'Dwyer - CppCon 2020". At around the time mark 6:45 it says: "Every write to a single memory location must be synchronise-with all other reads or writes of that memory location, or else the program has undefined behavior".
    And that's why there's a bit more behind concurrency than simply spawning multiple threads ;)
    But otherwise nice video that shows in simple ways how to create and join threads in C++ :)

  • @kapilchauhan7954
    @kapilchauhan7954 Před 2 lety +2

    If tutor is going in nature, why should we study in room, I'm watching this in nature.
    Cherno you are amazing brother ❤️❤️

  • @igorszemela1610
    @igorszemela1610 Před 2 lety

    brilliant vid, thx

  • @ultimatesoup
    @ultimatesoup Před 9 měsíci

    My game engine uses a thread pool that I've written along with coroutines for the different components and a scheduler class. The scheduler determines how long and when each component should run based on amount of work and priority and because they're coroutines its easy to suspend them at many points, save their state, and then pick up execution from there during the next frame

  • @RiverBeard
    @RiverBeard Před 3 lety

    Cherno you are a hero!

  • @pritampatil4163
    @pritampatil4163 Před 2 lety

    hey charnya its amazing series

  • @nielsdaemen
    @nielsdaemen Před 5 lety

    I love the fact that you are doing this in the forest!

  • @yuanjiewu9132
    @yuanjiewu9132 Před 6 lety

    It's easy to understand, thanks.

  • @monsieurcotcot
    @monsieurcotcot Před 2 lety

    powerful for image processing

  • @ma08serrano
    @ma08serrano Před 6 lety

    Finally. I am waiting this.

  • @petarsmilajkov9431
    @petarsmilajkov9431 Před 6 lety

    Need more videos in C++ series! :)

  • @1889990
    @1889990 Před 6 lety +92

    You should have mentioned Race Conditions which are probably the most common problem with threads. Still nice simple introduction.

    • @NeoKailthas
      @NeoKailthas Před 3 lety +1

      Thanks for this comment. I didn't realize they are related.

    • @puppergump4117
      @puppergump4117 Před 2 lety +4

      @@NeoKailthas Yeah race is a big problem especially with different colored threads

    • @Henry14arsenal2007
      @Henry14arsenal2007 Před rokem

      @@puppergump4117 Whats thread coloring?

    • @puppergump4117
      @puppergump4117 Před rokem +1

      @@Henry14arsenal2007 A race issue lol

    • @Henry14arsenal2007
      @Henry14arsenal2007 Před rokem +2

      @@puppergump4117 lol i just only now got that it was a joke, legit thought thread coloring was a concept in programming (which i was hearing of for the first time in my years of studying and practice).

  • @dirtyblasion15
    @dirtyblasion15 Před 6 lety +140

    No mutex or atomic :/

    • @warrenbuckley3267
      @warrenbuckley3267 Před 5 lety +30

      I would also like to see thread synchronization covered.

    • @poganka45
      @poganka45 Před 5 lety +4

      @@warrenbuckley3267 me too me too

    • @nazardidkovskyi
      @nazardidkovskyi Před 5 lety +8

      No std::future or std::async :/

    • @eddyecko94
      @eddyecko94 Před 4 lety +3

      He just uploaded a video on it

    • @BlacKHellCaT78
      @BlacKHellCaT78 Před 4 lety

      @@warrenbuckley3267 and thread safety, race conditions etc

  • @danielkupisinski7231
    @danielkupisinski7231 Před 6 lety +1

    love the birds in the background xd

  • @openroomxyz
    @openroomxyz Před 2 lety +1

    if you print very fast, in background thread, and you don't use std::endl but you use
    then it goes into new randomly.
    "
    " Outputs a newline (in the appropriate platform-specific representation, so it generates a "
    " on Windows), but std::endl does the same AND flushes the stream.

  • @clintsheppard9699
    @clintsheppard9699 Před 3 lety

    The aussie forest background sounds were a vibe

  • @SaratAnimation
    @SaratAnimation Před 6 lety

    Thanks!

  • @Sherrygamespvtltd
    @Sherrygamespvtltd Před rokem

    very well explained.

  • @dochaar
    @dochaar Před 2 lety

    Thanks for the great video! Can you please do a follow up video on how Future, Promise and Coroutines work in C++?

  • @kurciqs8355
    @kurciqs8355 Před 2 lety

    teaches threads in da woods. legend

  • @user-eh5zk5bb9k
    @user-eh5zk5bb9k Před 3 lety

    awesome!

  • @jamespong6588
    @jamespong6588 Před 4 lety

    FYI open gl is single threaded
    ....
    I use threads in all my heap allocations but I try not to have more than 2 threads running at the same time.
    Also it's better to abandon oop and have your threads in one function with a switch loop, and each case calling a single function
    (then the function calls the classes etc)

  • @lKOKOLIZO
    @lKOKOLIZO Před 6 lety +16

    EXCEPTIONS Chernobyl

  • @DuyTran-ss4lu
    @DuyTran-ss4lu Před 5 lety

    Thanks

  • @rcookie5128
    @rcookie5128 Před 6 lety

    thanks!

  • @reductor_
    @reductor_ Před 6 lety +4

    The code in this video is not thread safe, s_Finished should be atomic, it is perfectly acceptable for the compiler/machine to only do the read once for that boolean value if it can determine it is not changed anywhere throughout that function, in which case it won't see it become true.

  • @senatorpoopypants7182
    @senatorpoopypants7182 Před 6 lety

    Hey cherno loving this as always still waiting a course on algorithms and data structures

  • @Narblo
    @Narblo Před 6 lety

    Awesome!

  • @swoopertr
    @swoopertr Před 6 lety

    you are the best!

  • @bulentgercek
    @bulentgercek Před 4 lety +3

    11:16 His camera man says "It's done?" :D

  • @user-vp5is8mi4x
    @user-vp5is8mi4x Před rokem

    شرح حلو عاشت ايدك ♥👏

  • @babythedude
    @babythedude Před 5 lety

    well said

  • @mateusinkkj
    @mateusinkkj Před 3 lety +1

    I LOVE YOU AND YOUR CHANNEL IS FANTASTIC IM BRAZILIAN BRO

  • @ryanmckenna2047
    @ryanmckenna2047 Před 2 lety

    Nice forest!

  • @perfectionbox
    @perfectionbox Před 4 lety

    i'm glad that modern PCs are multicore because in the old days, one could have threaded code that worked but only because all the threads were scheduled on a single CPU (i.e., software threads), getting discrete time slices and not truly running in parallel. The code would then fail on a multiprocessor system surprising the developer. But now we can rigorously test right away. Even release vs. debug builds can differ!

  • @rohanyadav7327
    @rohanyadav7327 Před 6 lety

    Hi cherno , please make video on recursion in c++ & how it works internally.

  • @Driver___
    @Driver___ Před 6 lety

    Threads! Finally!

  • @xeekk
    @xeekk Před 6 lety +2

    I almost didn't recognize you until you did the hands :-)

  • @yabastacode7719
    @yabastacode7719 Před 6 lety

    I like the nature

  • @ChrisVideosGreek
    @ChrisVideosGreek Před 3 lety

    AmaZING! Thank you. Now l can run 2 things together!

  • @Mibbzz
    @Mibbzz Před 3 lety +1

    I work at home in a room with my pet birds, and they are going NUTS from the bird sounds in the background lol

  • @frootube5662
    @frootube5662 Před 5 lety +33

    9:26 does nobody want to tell me what that sound was

    • @iliashdz9106
      @iliashdz9106 Před 4 lety +18

      thas a phantom from minecraft

    • @shibakaneki555
      @shibakaneki555 Před 4 lety

      I would say that’s a jay (bird)

    • @ChrisMunz280
      @ChrisMunz280 Před 4 lety +4

      Probably a pterodactyl

    • @stephen9849
      @stephen9849 Před 3 lety +2

      That sound was made by a "wild cherno", it's a rare animal found in the woods who codes in C++.
      Nature is so beautiful!

    • @amp2amp800
      @amp2amp800 Před 3 lety

      bigfoot

  • @Fabbethe1st
    @Fabbethe1st Před 6 lety

    @TheChernoProject will you ever go in to true parallel programing without shared memory. Like how to use MPI for example?

  • @h.hristov
    @h.hristov Před 6 lety

    More threading videos!

  • @xxdeadmonkxx
    @xxdeadmonkxx Před 4 lety

    Thanks for the video, i wonder if boolean variable could be cached and never get new value?

  • @gabrielbraz9669
    @gabrielbraz9669 Před rokem

    Some questions i have:
    - How would I make differents thread accessing and updating the same value to always have the most up to date value?
    - And also, how many threads can I initialize? My pc has 16 threads, so is that the maximun I can start? Or if a start more than that the OS will handle how each thread will run?

  • @lschua5571
    @lschua5571 Před 5 lety

    Can this treads be used as Interrupt? My C++ project got safety concern. It need to do interrupt when safety button trigger. Then execute machine stop function & power down machine immediately.

  • @bluebacon1169
    @bluebacon1169 Před 4 lety +3

    why do you sometimes use "
    " and other times use std::endl?

  • @sfafsashfdh6589
    @sfafsashfdh6589 Před 2 lety

    imagine hiking in woods and seeing guy speaking about threads in cpp

  • @tommy7788
    @tommy7788 Před 5 lety +1

    What is the advantage of using thread header over MPI or OpenMp?

  • @automatic241
    @automatic241 Před 6 lety

    That Resolution, oh boi.

  • @shihabahmed2809
    @shihabahmed2809 Před 4 lety

    subscribed

  • @GamerSaga
    @GamerSaga Před 6 lety

    hey there, hoping for you thoughts on this. wish to make a fake 3d style fps rpg with a physics engine to help simulate abilities like telekinesis and such. wish to build from scratch though not sure of the mathimatical requirments to understand and anything else that would be needed. would be using c++ and not look to make it very complex just enough to simulate what i want. if possible? any suggestions or advice? would the sparky engine in your tutorials work for it?

  • @devprakash5320
    @devprakash5320 Před 2 lety

    fuck , he explained it so well

  • @AntiWanted
    @AntiWanted Před 3 lety

    Nice

  • @andreashadjiantonis2596
    @andreashadjiantonis2596 Před 5 lety +2

    Isn't accessing the same non-atomic variable in two different threads wrong? (i know that you're only mutating it in only one of two threads, but still).
    Nice video btw.
    Thanks!