Safety and Speed Issues with Threads. (pthreads, mutex, locks)

Sdílet
Vložit
  • čas přidán 12. 07. 2024
  • Patreon ➤ / jacobsorber
    Courses ➤ jacobsorber.thinkific.com
    Website ➤ www.jacobsorber.com
    ---
    Safety and Speed Issues with Threads. (pthreads, mutex, locks) // People often get really excited about threads when they first learn, but threads come with some challenges. This video talks about some of those challenges, like race conditions, and how to keep things sane using synchronization primitives like mutex locks.
    Prior pthreads videos.
    • How to create and join...
    • How to pass arguments ...
    Sockets example
    • How to build a web cli...
    ***
    Welcome! I post videos that help you learn to program and become a more confident software developer. I cover beginner-to-advanced systems topics ranging from network programming, threads, processes, operating systems, embedded systems and others. My goal is to help you get under-the-hood and better understand how computers work and how you can use them to become stronger students and more capable professional developers.
    About me: I'm a computer scientist, electrical engineer, researcher, and teacher. I specialize in embedded systems, mobile computing, sensor networks, and the Internet of Things. I teach systems and networking courses at Clemson University, where I also lead the PERSIST research lab.
    More about me and what I do:
    www.jacobsorber.com
    people.cs.clemson.edu/~jsorber/
    persist.cs.clemson.edu/
    To Support the Channel:
    + like, subscribe, spread the word
    + contribute via Patreon --- [ / jacobsorber ]
    Source code is also available to Patreon supporters. --- [jsorber-youtube-source.heroku...]

Komentáře • 90

  • @mayboy401studios
    @mayboy401studios Před 3 lety +109

    You are making my masters degree run at log n runtime, i love this so much!

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

      Is this a masters course? I'm a batchelor sophomore and I'm learning this

    • @Ethan-rw7ub
      @Ethan-rw7ub Před 2 lety +11

      @@cyberflaw_ there are definitely multiple levels to this, doesn't matter if you are a bachelor or a masters student

    • @vcv6560
      @vcv6560 Před 11 měsíci

      I see what you did there nice touch

  • @MrUmang40
    @MrUmang40 Před 5 lety +49

    You are legend.....Thank you for being with us.....

  • @SachithNalakaMuhandiram
    @SachithNalakaMuhandiram Před 4 lety +15

    This is not an ordinary "How to Be a C programmer" guide.

  • @angelabarsallo153
    @angelabarsallo153 Před 3 lety +17

    You sir are a legend. Taught me in 9 minutes what my professor couldn't effectively teach in 2 hours. Thank you so much!! Your videos are very well done and super easy to understand

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

    Hi Jacob, Thank you from my heart to sharing your knowledge on this topic. Really really appreciate the time and effort you must have invested to create this video. I can only understand and appreciate the time it took you to edit out those millisecond pauses in between those sentences. I was looking for such type of quality explanation of thread in c. Keep making these videos. Thank you so much.

  • @joaomarcosqueirozlopes6227
    @joaomarcosqueirozlopes6227 Před 5 lety +12

    your explanations are really helpful, keep it up. thanks

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

    I am really enjoying your videos.Please continue making amazing videos like this. Hope to see more videos from you. Thanks a lot.🤗

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

    Fantastic! Very clear explanation, objective and practical.
    Thanks.

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

    You're helping me a lot to understand all of this. THANKS

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

    Your videos are really clear and helpful! Thanks for making them and uploading them!

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

    Thanks a LOT for your clear concise (interactive) explanation.

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

    Your video is super helpful for me to prepare my lab. Thank you!!!

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

    thank you !!! you are helping me alot with this subject... keep up posting videos, you make it fun to learn C. :)

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

    This is fantastic! Such clear and concise explanations of some really difficult topics!

    • @JacobSorber
      @JacobSorber  Před 3 lety

      Thanks, Christin. Glad they're helpful.

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

    You are a legend and my savior. Thank you for the amazing videos and please never stop. You're making code much more easy for me. I truly appreciate that. Props from Portugal!

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

      Wow, thanks! Will keep doing what I can to help.

  • @electruc3370
    @electruc3370 Před 3 lety

    This channel is which I looking for a long time.
    Thank you for sharing.

  • @user-tj2qj5tm1f
    @user-tj2qj5tm1f Před 2 lety

    left the sub. best man! embedded systems master is now so easy with your videos
    THX!!!

  • @user-xm2iy1ch7n
    @user-xm2iy1ch7n Před 7 měsíci

    Really good video….thanks for sharing the knowledge 🙂

  • @uboxer
    @uboxer Před 2 lety

    Brilliant!

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

    Great videos as always, I really appreciate the effort you put in. I was having a hard time grasping mutex locks and conditional variables and this really helped. Usually I find the man-pages sufficient but the pages for mutex locks didn't really give a nice overview.

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

      Agreed. The man pages for pthreads sometimes falls short. Glad I could help.

  • @ronaldfungss
    @ronaldfungss Před 10 měsíci

    Thank you Jacob : ]

  • @faceless4970
    @faceless4970 Před rokem

    you are master piece channel to me

  • @GeekyMino
    @GeekyMino Před 4 lety

    Great video!

  • @salihylmaz4694
    @salihylmaz4694 Před 5 lety

    Great video

  • @oumaymamazoz3385
    @oumaymamazoz3385 Před 2 lety

    thank u so much u helped me too much

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

    Definitely, I like your explanation, but as I am not a pre-intermediate user of c language little difficult for me this thread concept. Well done guy you are the best

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

      If it makes you feel better, threads are challenging for a lot of people to wrap their heads around.

  • @andrearamirez722
    @andrearamirez722 Před 3 lety

    How are there 10 minute youtube videos more educating than my 100dls 1 hour lectures???? Thank you!!!!

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

    great video! hope see more video from u

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

    Where does the soundbite from the intro come from? Sounds really good.
    As always superb videos man, I really appreciate your work.

    • @JacobSorber
      @JacobSorber  Před 4 lety

      Thanks. Glad you liked it. The song's from the CZcams music library.

  • @mushahidhussain1516
    @mushahidhussain1516 Před 3 lety

    man that hmmmm intro music was so cool XD

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

    In the example you used a global variable. Can I assume threads respect normal rules of scope?
    Does each thread have local variables if declared in the thread? Does variable masking apply?
    If so, it seems race conditions are only created when threads are editing memory at address with a de referenced pointer or a global as shown in the example.
    Am I correct in this assumption?

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

      Global variables can be used as shared memory between threads. When u use "shared memory" between threads or even processes there is always the problem with race condtitions. Local variables can also be shared if the other thread have a pointer to it. Global variables are more risk free because they only get deallocated when the whole process terminates. If u use local variables as shared memory you have to be carefull when it gets deallocated, especially when its in the stack.

  • @indyarockers
    @indyarockers Před 5 lety

    Thank you for such a nice explanation. You have used variable 'i' in for loop in your earlier video "How to create and join threads in C (pthreads)", how it worked there?

    • @JacobSorber
      @JacobSorber  Před 5 lety

      In that video, I used "i" as a loop counter, mostly to repetitively print stuff out so you could see what the threads were doing and that they were actually interleaving their executions.

  • @nhan99dn
    @nhan99dn Před 2 lety

    🙌

  • @prashantgaur5123
    @prashantgaur5123 Před 5 lety

    Hi Jacob,
    hope you doing great .
    People often comment on response speed of
    semaphore,thread -semaphore and mutex.( spinlock is the mechanism for all these three)....
    please comment on how their response time differ from each other & why

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

      This depends a lot on how they are each implemented. The common wisdom is that spinlocks are sometimes best if wait times are very short because they don't cause extra context switching and data structure operations. I've seen spinlocks used often in kernel and device driver code, presumably for that reason. As for the others, if the performance difference mattered to me, I would test them experimentally, because you could have a fast or slow implementation that could make a big difference. Note that you can use semaphores to implement mutexes and vice versa.

  • @69k_gold
    @69k_gold Před rokem

    Threads are basically good at what they're meant to be.. doing multiple tasks at the same time. The definition of a task is pretty important here. It should mostly be a completely independent process or set of processes from other tasks.

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

    Are you uploading the source code of your examples?

  • @yasinkhan4620
    @yasinkhan4620 Před 4 lety

    Great video, may I ask about the name of that opening song?

    • @JacobSorber
      @JacobSorber  Před 4 lety

      Don't remember off the top of my head. It's one of the free-to-use songs from the YT library, though.

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

    Nice video. How to debug a multi threaded code using gdb ?

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

      That's going to be one of my next videos. Hopefully, coming soon.

  • @soniablanche5672
    @soniablanche5672 Před 2 lety

    the thread unsafe version is slower than sequential because i is not being updated correctly, it's possible that one thread is redoing the loop again because it's incrementation was overridden.

    • @sverkeren
      @sverkeren Před 2 lety

      No, "i" is a local stack allocated variable, specific to each thread.

  • @knight024
    @knight024 Před 5 lety

    How does async compare to threads? Is the fundamental core component of async pretty much a loop that processes queue'd tasks? Does the operating system have to use kqueue or epoll type of event notification at the OS kernel level to let the PID know an event is not blocked and ready for a read or write operation?
    If you can clear this up in a video that would be awesome!

  • @HamishArb
    @HamishArb Před 2 lety

    In C# I use Interlocked.Increment(ref x);

  • @islandcave8738
    @islandcave8738 Před 2 lety

    Threads, one main thread, one thread for curl requests, one thread doing socket communication...

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

    i don't get it -- wouldn't i get reinitialized with each function call? how do the two calls "divide up" the work?

    • @sverkeren
      @sverkeren Před 2 lety

      Non static local variables are thread specific. Each thread has its own stack and local variables are stored on the stack.
      Global variables, on the other hand, are shared between the threads. In this example both threads access the same global "counter" but different local "i".

  • @sudarshanv9797
    @sudarshanv9797 Před 3 lety

    In windows for gcc
    command line for thread based program is
    gcc -pthread -o main main.c

  • @low-key-gamer6117
    @low-key-gamer6117 Před 2 lety

    Came here when my printf started putting out weird outputs when running threads

  • @the_biggest_chungus7508

    Mr Sorber, may I get your opinion on an idea of mine? I want to create a Cobot, which means a robotic Chassis with four Mecanum-Wheels a robot arm and some sensors (LADAR/Ultrasonic or a camera for navigation, a Gyro and some torque sensors for the arm). For the sake of curiousity and performance I want to run the source code in multiple threads. Its supposed to work as followed:
    First, the main() initializes the Cobot, gets the initial sensor datas etc.
    Second, the main() creates four threads, one per wheel, and lets them handle the movements of the wheels according to the required speed and direction.
    So instead of processing everything in one thread, I'd like to outsource the drive controls which can be *really* complex and difficult and let the main thread act as a Master in a Master/Slave config. It would let the Slave-threads work independently and just throw in Interrupts or similar if the need occurs. For example a new operator command. A bit like a Star-topology of Threads. Would you give that idea a go or is it to far off of reality?
    Best regards :)

  • @phandc4581
    @phandc4581 Před 3 lety

    It's very informative. As a CS student, I would feel very appreciate if you upload all the source codes on Github. You deserve to have more supports. Thank you very much!

  • @JohnHollowell
    @JohnHollowell Před 5 lety

    CUhackit shirt!

  • @BROTHERsGAMinglive
    @BROTHERsGAMinglive Před 3 lety

    you are the person which i want to be

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

    I'd like to see your solution to scale the program. My solution would we to give both threads their own counter and the add the counters after the join.

  • @nitinparmar8350
    @nitinparmar8350 Před 3 lety

    Hi Jacob can you send this client server code ?please.....

  • @TheBigW300
    @TheBigW300 Před 4 lety

    why wouldn't you just show that if you made two local variables for each thread then added them at the end would be a fast parallel solution to the counting problem? Because you sorta made it seem as if there was no way to count to a billion with parallelism but there is.

  • @atharvasuryawanshi7675
    @atharvasuryawanshi7675 Před 8 měsíci

    03:20 you are wrong there buddy

  • @jimivie
    @jimivie Před 2 lety

    mmm.....bacon

  • @zes3813
    @zes3813 Před 2 lety

    no such thing as scaryx or diffx or not, no nerx, diffxs s not scary either

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

    vegetarians do not agree.

    • @JacobSorber
      @JacobSorber  Před 2 lety

      Do they think threads *are* bacon? Or, maybe that threads don't have speed and safety issues? 🤔

    • @piotrjozef8797
      @piotrjozef8797 Před 2 lety

      @@JacobSorber I suppose that they wouldn't agree that adding bacon makes everything delicious. :P

    • @JacobSorber
      @JacobSorber  Před 2 lety

      @@piotrjozef8797 Oh, that. Yeah, you're might be right. :)

  • @yonahweiner
    @yonahweiner Před 2 lety

    this was great clickbate. mmm bacon

  • @jacko314
    @jacko314 Před 2 lety

    i normally love your videos. this was really poorly put together. first of all i++ is actually usually optimized down to a single inc instruction depending on the complexity of the function. so that was just blatently wrong. also using global variables in a multithreaded application is ridiculous. i know OS's have done it, python does it. in the end it ends in tradegdy. simple rule: if you need to synchronize between threads then make it very quick and don't do any io while holding a lock unless absolutely vital, especially in kernel mode.

    • @jacko314
      @jacko314 Před 2 lety

      and again if you are doing processing on large peices of memory the atomic instructions are a vital tool and they should be used. yes you should have a strong grasp of low level programming at this point, but you are programming in C so that should be a given. locks like mutexs are awefull for performance. chache flushes ect. a C programmer should be aware of these things or just go write some python or javascript. most of my code i've written has been in a multithreaded environment, ie: windows kernel and user mode services which is event driven. ie: you are called in an arbitrary thread context of the process preforming io. and things like mutexs can kill your performance. there are cache safe counter mechanisms that allow you to get around many issues mentioned here. ok ok enough ranting. if you go multithreaded you should know what you are doing, but that is the life of a C programmer. simple rules to follow: don't do any IO while holding a lock. if your problem can be broken into easy chunks without locks do that: enc(0..1024), enc(1024...2048) ect. also having a master thread helps. i'd advise that. most C programmers aren't aware of spin locks, but they are super powerfull if used properly, especially with a master thread and interlocked operations. again, love the vids.