Lab Exp07:: Prevention of Race condition using mutex in C programming in multithreaded process
Summary
TLDRThe video script discusses the issue of race conditions in multi-threaded programming, demonstrating how a shared variable can be incorrectly incremented due to improper context switching. It then shows how to resolve this using a mutex, a synchronization mechanism that ensures mutual exclusion, thus preventing race conditions by allowing only one thread to access a shared resource at a time. The script concludes with a demonstration that, with mutex in place, the final value of the shared variable consistently reaches the expected two million, regardless of thread execution order.
Takeaways
- 🔒 The script discusses the problem of race conditions in multi-threaded programming.
- 📝 The issue arises when two threads try to increment a shared variable, expecting a final value of two million but getting inconsistent results.
- 👷♂️ The script demonstrates how to resolve race conditions using mutexes, which provide mutual exclusion for shared resources.
- 🔨 Mutexes are declared and initialized using specific pthread functions to ensure safe access to shared data.
- 🔒🔒 Before accessing the shared variable, threads must lock the mutex with `pthread_mutex_lock`.
- 🔓 After updating the shared variable, threads must unlock the mutex with `pthread_mutex_unlock`.
- 🛠️ The script shows the implementation of mutex locking within the threads' increment loop to prevent race conditions.
- 🔄 The use of mutex ensures that only one thread can update the shared variable at a time, blocking others until the lock is released.
- 💡 The script illustrates that with mutex locking, the final value of the shared variable consistently reaches the expected two million.
- 🔄 The script mentions that the order of thread execution may vary, but the use of mutex ensures a consistent outcome.
- 🚀 The script concludes by stating that mutexes and semaphores can effectively address race conditions, with a follow-up session planned to discuss semaphores.
Q & A
What is the primary issue discussed in the video script?
-The primary issue discussed in the video script is the race condition in multi-threaded programming, where two or more threads access a shared variable simultaneously and lead to unpredictable results.
What was the expected outcome if the shared variable was incremented correctly by two threads one million times each?
-The expected outcome would be that the final value of the shared variable should be two million, as each thread increments the value one million times.
What is the actual result observed when the race condition occurs?
-When the race condition occurs, the final value of the shared variable is not consistent and varies with each execution, deviating from the expected two million.
How is a mutex used to solve the race condition problem?
-A mutex (mutual exclusion) is used to ensure that only one thread can access a shared resource at a time. It is used to lock and unlock access to the shared variable, preventing simultaneous access and thus avoiding the race condition.
What function is used to declare a mutex variable in the script?
-The function used to declare a mutex variable in the script is pthread_mutex_t.
What function is used to initialize a mutex variable?
-The function used to initialize a mutex variable is pthread_mutex_init, which takes the address of the mutex variable and an optional attributes argument.
What are the two functions used to control access to the shared variable using a mutex?
-The two functions used to control access to the shared variable using a mutex are pthread_mutex_lock and pthread_mutex_unlock.
What happens when a thread calls pthread_mutex_lock?
-When a thread calls pthread_mutex_lock, it attempts to acquire the lock on the mutex. If the lock is already held by another thread, the calling thread will be blocked until the lock becomes available.
How does using a mutex ensure the correct final value of the shared variable?
-Using a mutex ensures that only one thread can update the shared variable at a time, preventing simultaneous updates that could lead to incorrect values. This sequential execution guarantees that the final value will be the expected two million.
What is the next topic the speaker mentions will be discussed in the next session?
-The next topic the speaker mentions will be discussed in the next session is semaphores, which are another synchronization mechanism to handle similar issues as mutexes.
Outlines
🔒 Introduction to Mutex for Solving Race Conditions
This paragraph introduces the concept of race conditions in concurrent programming, where two or more threads access shared data simultaneously, leading to unpredictable results. The speaker demonstrates the issue using a code example where two threads are incrementing a shared variable one million times each, expecting a total of two million but getting inconsistent results due to race conditions. To address this, the speaker suggests using a mutex (mutual exclusion) to ensure that only one thread can access the shared resource at a time. The mutex is declared globally and initialized within the main function using specific functions. The speaker explains the process of locking and unlocking the mutex around the critical section of code to prevent race conditions.
🛠 Implementing Mutex to Prevent Race Conditions
In this paragraph, the speaker continues the discussion on mutexes, explaining how to apply them in a multi-threaded environment to prevent race conditions. The speaker provides a step-by-step guide on using mutex functions such as 'pthread_mutex_lock' and 'pthread_mutex_unlock' to lock and unlock the mutex, respectively, ensuring that threads access the shared variable in a mutually exclusive manner. The speaker also discusses the importance of the order of operations: locking the mutex before updating the shared variable and unlocking it afterward. The paragraph concludes with the speaker executing the modified code with mutex implementation, which successfully produces the expected result of two million, demonstrating that mutexes effectively solve the race condition issue.
Mindmap
Keywords
💡Race Condition
💡Shared Variable
💡Thread
💡Mutex
💡Context Switching
💡Pthread_mutex_t
💡Pthread_mutex_init
💡Pthread_mutex_lock
💡Pthread_mutex_unlock
💡Sequential Execution
💡Semaphore
Highlights
Demonstration of the issue of race condition in multi-threaded programming.
Explanation of shared variable and its manipulation by two threads to increment its value one million times each.
Observation of inconsistent final values due to inappropriate context switching, leading to race conditions.
Introduction of mutex as a solution to handle race conditions in shared resources.
Declaration of a global mutex variable to ensure mutual exclusion access.
Initialization of the mutex variable using pthread_mutex_init function.
Use of pthread_mutex_lock to acquire the mutex lock before accessing shared data.
Implementation of mutex locking within the thread function to prevent simultaneous access to the shared variable.
Unlocking the mutex with pthread_mutex_unlock after updating the shared variable to allow other threads.
Compilation and execution of the modified code with the pthread library.
Observation of consistent final values of the shared variable after implementing mutex locks.
Demonstration of sequential execution on shared resources due to mutex locking.
Explanation of how mutex prevents race conditions by ensuring one thread's execution before another.
Execution of the program multiple times to show the fixed final value of the shared variable.
Introduction of the next session's topic: dealing with race conditions using semaphores.
Conclusion of the session with a summary of how mutex and semaphores can address race conditions.
Thank you message and closing of the session with music.
Transcripts
foreign
[Music]
I have demonstrated the issue or problem
of risk condition
so in this session I am going to
demonstrate you how to deal with the
race kind of situation
so let's look at the previous code which
we have already seen
in this code actually we have
defined one shared variable named as
shared
and then I have created two threads of
the same process
and this two threads were trying to
increment the value of shared variable
and it was trying to increment the value
of the shared variable one million times
okay
and we got to know that because of the
context switching in appropriate context
switching there was a problem of race
condition
so in this situation we were expecting
if there are two threads and both are
incrementing the value of shared
variable one million times if both will
execute successfully the final value of
this shared variable need to be two
million right
but if we execute this code as we have
already discussed in the previous
session
so let me compile this and let's say we
executed
it is giving not 2 million it is giving
something else so if I again
compile it the final value of the shared
variable it is displaying different
different values right
so it is displaying different value then
again different value then again
different value and so on so that means
there is a raise condition the final
value which is we are expecting here it
is not same every time right
so to deal with this situation what we
can do is
let's modify the previous code
okay
so we can
deal with such kind of situation with
the help of either mutex or Shima power
so till now I haven't elaborated ishma
for so let's deal with the race
condition with the help of mutex
so I need to declare a global kind of
mutex variable so
we know that how we can declare
the mutex kind of variable you can use P
thread
underscore mutex
underscore
T function or t variable P thread
underscore mutex underscore T and let's
see I am giving this name as mutex okay
so this is the mutex
which has been defined as the global
mutex variable
now this mutex let's say inside the main
function
I would initialize so let's say I
initialize the mutex so P thread
underscore mutex
underscore init function we can use to
initialize the mutex
and this function takes two arguments
one is the pointer of mutex types and
another
some default argument if you want to set
so the very first thing is the address
of mutex variable which we want to
initialize
and the second variable we can set as
null
okay
so it will initialize the mutex variable
with default
attributes right
now how we are going to use this
actually mutex
we used to provide Mutual exclusive
access of shared resources like critical
sets so if there are
multiple threads or n number of threads
are there they are operating on the same
shared data
before accessing the shared data we can
call
mutex
underscore you can say log okay so P
thread underscore mutex underscore log
is one of the function which every
thread need to call before acquiring or
before operating on the shared resource
here the shared resources actually the
shared variable
so in this Loop which I have written in
this thread underscore function this
Loop is actually incrementing the value
of shared variable
so let us look at here we need to apply
P thread underscore mutex underscore log
before
updating the shared variable
the mutex need to be acquired by every
function or you can see every thread
right
so here we need to pass the address of
mutex variable and the name of the mutex
variable is one this that mutates only
right so I am passing ampersand mutex
and once we finish the updation of the
shared variable we can unlock develop so
P thread underscore mutex
underscore unlock
okay
and then
address of mutex variable I have passed
okay so I hope you are already familiar
with these two functions P thread
underscore mutex underscore lock and P
thread underscore mutex and S4 unlock
now once we do this
well a function calls this particular
when a thread calls this particular
function
it will first acquire the lock on the
mutex so in the same duration when let's
say thread one is executing and updating
the shared variable
one million times if another thread also
want to acquire the lock on the same
mutex it will be blocked okay
so this will solve the problem of
rage condition
because
whatsoever the thread will acquire the
log first second well second thread will
be able to acquire the lock after the
execution of first one so because of
that sequential execution will be done
on the shared resources
and it will not lead to any of the
press condition so let's execute it
now
for compiling this we can use GCC and we
need to link the library so we can use
LP thread
Library
it is executed fine no issue and then
dot slash a DOT out to run this
particular program when we are running
you can check it
thread 0 is updated shared variable till
1 million and the shared one updated the
shared variable up to 2 million right so
if you execute it
the sequence the values and everything
is fine now in these two run the thread
one will execute it first dense thread
one thread zero executed first then
thread one but in this third time when I
have executed thread one executed first
then thread zero executed second time
but the final value of the shared
variable is fixed
so in whatsoever
the situation is whether thread 0 is
executing fast or thread one final value
of the shared variable will be fixed
right so I am executing it multiple
times
and the final value of set variable it
is 2 million
so that means with the help of mutex and
semaphores
this situation which we consider a risk
condition can be
dealed with right
so this is sufficient for this
particular session right in next session
I will talk about this Mr for variable
and the similar kind of situations
we will deal with the help of semapher
well right
[Music]
[Music]
thank you
[Music]
foreign
Ver Más Videos Relacionados
Lamport's Mutual Exclusion Distributed Systems Synchronization
How JavaScript Works 🔥& Execution Context | Namaste JavaScript Ep.1
L-3.2: Producer Consumer Problem | Process Synchronization Problem in Operating System
L-3.4: Critical Section Problem | Mutual Exclusion, Progress and Bounded Waiting | Operating System
L-3.7: Turn Variable | Strict Alteration Method | Process Synchronization
Difference Between Volatile, Atomic And Synchronized in Java | Race Condition In Multi-Threading
5.0 / 5 (0 votes)