Mutex Synchronization in Linux with Pthreads

Mutex Synchronization in Linux with Pthreads
Demo of using threads in Linux (pthreads) to run very simple processing in parallel. Uses a mutex (pthread_mutex) to synchronize the processing to avoid a race condition.
Support videos via Patreon: https://www.patreon.com/DrBFraser

- Timing the process without using threads (Linux time command)
- Switching processing to new threads
- Running multiple threads without a mutex lock (race condition)
- Solving a race condition
- Timing the multi-threaded version
- Common problem when passing arguments to a thread
- Common problem spotting race conditions

Create a single thread: http://youtu.be/ynCc-v0K-do
Eclipse Setup: http://youtu.be/E36QpJdEghg
Linux programming play-list: https://www.youtube.com/watch?v=E36QpJdEghg&list=PL-suslzEBiMrqFeagWE9MMWR9ZiYgWq89

RRelated Posts

pthreads #1: Introduction

Demo creating a thread in Linux to add up some numbers. Pass values to thread function as a pointer, return answer as a global variable. Full code can be found at

Difference between blocking and deadlocking

deadlock vs blocking sql server In this video we will discuss the difference between blocking and deadlocking. This is one of the common SQL Server interview question. Let us understand the


  • Linda Lu
    Found this video randomly when i am studying for a OS final and noticed that this video is actually made by the professor of my very first computer science course’s at a different school. Enjoyed your lecture just like before:)
  • Sinan Lin
    Yo, Dr.Bfraser. Do you have a tutorial for Semaphores ?
  • KommandoCraft
    would defining the whole loop as the critical section and therefore locking the mutex before it and unlockin after be an option? Wouldn't it drastically reduce the time required as we would only lock and unlock twice instead of a billion times? Or would that destroy the concept of multiple threads even if there would be more code other than this loop?
  • Victor-Alexandru Cuciureanu
    tommorow i have test , thx for the info
  • djavocard
    Good video. Only thing i wish you had explained how to optimize locking when you had ~5Billion NUM values (when the time went to 45s for 2 threads); Example Method explosion is 1 way probable to decrease execution time.
    count_thread (..) {... mutex_lock(..); .. new_method_sum(offset); .. mutex_unlock(..) }
  • aarti masal
    Can you add videos on shared memory access?
  • Trretedyteyfhjrfjtdjj
    I need a counting function to sum the number of likes I want to give this video
  • Akshay Shinde
    Thanks allot!can you make video on semaphore as well.?
  • George Tsiros
    so far you are the only one i managed to listen to for more than 30 seconds without closing the window in disappointment and frustration. Don't fail me now
  • Vu Duy Du
    Hello, I was testing on pthread with your tutorial, and I found out that, what make your thread running so slow is due to pthread_exit(NULL). When I replace it with return NULL, the thread run quite faster.
  • JK FRT
    This is a very interesting topic, thank you for the valuable information. Wondering about furexes now (fast user mutexes)... ;-)
  • JIN Park
    For those of you who are trying to figure out how to make mutex efficient as it should be,  you can just put the pthread_mutex_lock/unlock outside for loop. That's it.  putting lock() above the for loop and unlock() below the for loop solves everything which means , instead of protecting the access to a variable(sum), we'll protect the access to a for loop.
  • Evan Radcliffe
    Thank you so much for this video!
  • Judayle Dsouza
    Love the videos and all the practical information provided, extremely helpful.
    Also I found that Amdahl's law is a really simple but effective rule of thumb to think about whether you should use a multi threaded system or not.
  • Zheng SUn
    ur fking amazing man!!!
  • Giovanni Volpicelli
    God bless you <3
  • yihsiu chen
    Clearly explain pthread, really like it
  • Syuan Cheng Chen
    Thank you for providing a serial of useful tutorials. It really helps!
    For those who had trouble with "man pthread_mutex_lock" or others, just use the command "sudo apt-get install manpages-posix manpages-posix-dev" then it will work.
  • Hằng Nguyễn
    Thank you so much! This is really helpful.
  • CharlesBarkleyGG
    I wish I had found your videos the first time I took the operating systems course. Using them now. Thanks a lot.
  • B L Jangir
    Simply superb . Thanks
  • sin shad
    Great work!!!
    How can some one dislike this video :/
  • Rajeev Rajeev
    Awesome! I did the code in parallel as it was being done in the video.. It was fun and I would never forget it.
  • [ Kris ]
    Excellent video, thank you so much!
  • [ Kris ]
    13:29 So I need to protect access to sum in sum form of critical section
    (don't mind me it's a silly pun)
  • Varun Kumar
    super duper! it was fun watching... that's why programmers should be taught by programmers. theory can be learned on Google search
  • K Badsha
    I love redheads.
  • robheusd
    One should construct a loop-in-a-loop, the inner loop running for example N = 100 times, the outer loop NUM_LOOP divided by N, and place the mutex outside the inner loop and inside the outer loop. Experiment with different values for N (NUM_LOOP dividable by N).
  • ifyouwereasoup
    this is so weird.. it takes 3-5 times as long with threads on my machine (without the mutex lock), does anyone have an idea why?
  • Jon X Day
    You are absolutely amazing at this. Most demo's/tutorials that I've watched C, haven't been too good at clarifying the tidbits like the CPU Scheduling and changing the size of the loops. Absolutely amazing!
  • Daniel Nuno
    Nice video. I have a comment, shouldn't be the mutex lock and unlock outside the for statement?, so you don't have to do that amount of syscalls, regards.
  • Drake Gao
    so with large numbers, we not suppose to use multi-threads? How does this make sense? Thanks
  • O N
    Fantastic! Your lectures are superb. Thank you.
  • Linux Cow
    very educational , thx for sharing
  • Ivan Coleto
    great explanation!!
  • Alan Naidon
    Yo, Dr.Bfraser. Do you have a tutorial for Semaphores ?
  • Parnab Sanyal
    Lovely video
  • Victoria
    Very useful video, thank you!
  • Ovidiu Hozan
  • Across da maper Tamo'ahi
    You da real mvp
  • name8791
    clair et net ! merci chef
  • Gabriel Grama
    Hello ! Thank you! You explain very good and you give good example. Can you please make a video about semaphore ?
  • Pooja Kumari
    Awesome video!!!
  • Suryanarayan Mishra
    Awesome explanation !! Thank you Sir.
  • Abhijeet Awari
    this video is not for beginner ..I would suggest first read little bits about thread and then u can come back 2 this nice video...then u don't have to go 2 other video.
  • Abhijeet Awari
    your accent is  good we indian understand English ,but we don't really get English accent of foreigner ... I have gone through lots of thread video u r the 2 video which I found use full ...thanks for this video and keep it up doc. .
  • I don't even know.
  • shreejith kv
    Hi Dr Fraser. Can you explain why without the mutexes the sum calculated is wrong ( The two threads are complementing each other + 1 and -1 ).

    If we consider sum += offset as not an atomic operation.
    SUM = 0 //global

    Thread 1
    temp = sum + 1; // temp = 1
    --------------------> context swtich 1 -------------> Thread 2
    temp = sum - 1 // temp = -1
    <------------------ context swtich 2 <----------
    sum = temp; // sum = -1

    Here we can see that the thread1 that was supposed to do an increment is doing a decrement. This happens in random proportions leading to random results lying between [+2 * MAX_SUM_EXPECTED, -2 * MAX_SUM_EXPECTED ]

    My question is : Is such a context switching possible ( Just one instruction executed) ?
  • R Xander
    Very clear explanation. Thank you for sharing!