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

Поделиться
HTML-код
  • Опубликовано: 7 июн 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...]

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

  • @mayboy401studios
    @mayboy401studios 3 года назад +107

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

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

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

    • @Ethan-rw7ub
      @Ethan-rw7ub 2 года назад +10

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

    • @vcv6560
      @vcv6560 10 месяцев назад

      I see what you did there nice touch

  • @MrUmang40
    @MrUmang40 5 лет назад +49

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

  • @SachithNalakaMuhandiram
    @SachithNalakaMuhandiram 4 года назад +15

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

  • @angelabarsallo153
    @angelabarsallo153 3 года назад +16

    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

  • @joaomarcosqueirozlopes6227
    @joaomarcosqueirozlopes6227 5 лет назад +12

    your explanations are really helpful, keep it up. thanks

  • @makealemonade
    @makealemonade 2 года назад +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.

  • @abdelazizsaad7676
    @abdelazizsaad7676 3 года назад +4

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

  • @reydavid7300
    @reydavid7300 3 года назад +1

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

  • @viniciusnlage
    @viniciusnlage 3 года назад +1

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

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

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

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

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

  • @jiangfenglin4359
    @jiangfenglin4359 4 года назад +3

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

    • @JacobSorber
      @JacobSorber  4 года назад +2

      You're welcome. Glad I could help.

  • @competion19
    @competion19 4 года назад +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  4 года назад +3

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

  • @christinboicourt9053
    @christinboicourt9053 3 года назад +1

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

    • @JacobSorber
      @JacobSorber  3 года назад

      Thanks, Christin. Glad they're helpful.

  • @nadavzeldin
    @nadavzeldin 3 года назад +6

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

  • @user-xm2iy1ch7n
    @user-xm2iy1ch7n 6 месяцев назад

    Really good video….thanks for sharing the knowledge 🙂

  • @electruc3370
    @electruc3370 3 года назад

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

    • @JacobSorber
      @JacobSorber  3 года назад

      Welcome! Glad you're enjoying it.

  • @KarlKatten
    @KarlKatten 4 года назад +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  4 года назад +3

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

  • @user-tj2qj5tm1f
    @user-tj2qj5tm1f 2 года назад

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

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

    Thank you Jacob : ]

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

    Brilliant!

  • @faceless4970
    @faceless4970 11 месяцев назад

    you are master piece channel to me

  • @KarlKatten
    @KarlKatten 4 года назад +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  4 года назад

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

  • @GeekyMino
    @GeekyMino 3 года назад

    Great video!

  • @salihylmaz4694
    @salihylmaz4694 5 лет назад

    Great video

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

    thank u so much u helped me too much

  • @indyarockers
    @indyarockers 4 года назад

    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  4 года назад

      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.

  • @jacksonxie7579
    @jacksonxie7579 4 года назад +1

    great video! hope see more video from u

    • @JacobSorber
      @JacobSorber  4 года назад

      Thanks. Any specific topics?

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

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

  • @darkhanzholtayev3224
    @darkhanzholtayev3224 4 года назад +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  4 года назад +2

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

  • @nuse420
    @nuse420 3 года назад +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 2 года назад +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.

  • @JorgeVallecillo
    @JorgeVallecillo 5 лет назад +2

    Are you uploading the source code of your examples?

  • @prashantgaur5123
    @prashantgaur5123 5 лет назад

    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  5 лет назад +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.

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

    man that hmmmm intro music was so cool XD

  • @yasinkhan4620
    @yasinkhan4620 4 года назад

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

    • @JacobSorber
      @JacobSorber  4 года назад

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

  • @knight024
    @knight024 5 лет назад

    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!

    • @JacobSorber
      @JacobSorber  4 года назад

      Good idea. I'll see what I can do.

  • @kushagrakumar9576
    @kushagrakumar9576 5 лет назад +1

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

    • @JacobSorber
      @JacobSorber  5 лет назад +2

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

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

    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 Год назад

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

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

    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 :)

  • @alexleibowitz6448
    @alexleibowitz6448 4 года назад +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 Год назад

      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 3 года назад

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

    • @questionmarc8
      @questionmarc8 6 месяцев назад

      for gcc in general actually

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

    🙌

  • @69k_gold
    @69k_gold Год назад

    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.

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

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

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

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

  • @low-key-gamer6117
    @low-key-gamer6117 2 года назад

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

  • @phandc4581
    @phandc4581 3 года назад

    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!

  • @sghsghdk
    @sghsghdk 2 года назад +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 3 года назад

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

    • @JacobSorber
      @JacobSorber  3 года назад

      Code's available through patreon.

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

    you are the person which i want to be

  • @TheBigW300
    @TheBigW300 4 года назад

    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.

  • @JohnHollowell
    @JohnHollowell 5 лет назад

    CUhackit shirt!

  • @atharvasuryawanshi7675
    @atharvasuryawanshi7675 7 месяцев назад

    03:20 you are wrong there buddy

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

    mmm.....bacon

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

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

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

    vegetarians do not agree.

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

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

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

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

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

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

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

    this was great clickbate. mmm bacon

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

    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 2 года назад

      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.