Introduction to Mutex

What is Mutex
The mutex(short for mutual exclusion) also known as spinlock is the simplest synchronization tool that is used to protect critical regions and thus prevent race conditions. That is a thread must acquire a lock before entering into a critical section(In critical section multithreads share a common variable, updating a table, writing a file and so on), it releases the lock when it leaves critical section.

What is a Race Condition.
A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don’t know the order in which the threads will attempt to access the shared data. Therefore, the result of the change in data is dependent on the thread scheduling algorithm, i.e. both threads are “racing” to access/change the data.

Example:
Consider single toilet with a key. When someone enters, they take the key and the toilet is occupied. If someone else needs to use the toilet, they need to wait in a queue. When the person in the toilet is done, they pass the key to the next person in queue. Make sense, right?

Convert the toilet in the story to a shared resource, and the key to a mutex. Taking the key to the toilet (acquire a lock) permits you to use it. If there is no key (the lock is locked) you have to wait. When the key is returned by the person (release the lock) you’re free to acquire it now.

When I am having a big heated discussion at work, I use a rubber chicken which I keep in my desk for just such occasions. The person holding the chicken is the only person who is allowed to talk. If you don’t hold the chicken you cannot speak. You can only indicate that you want the chicken and wait until you get it before you speak. Once you have finished speaking, you can hand the chicken back to the moderator who will hand it to the next person to speak. This ensures that people do not speak over each other, and also have their own space to talk.

Replace Chicken with Mutex and person with thread and you basically have the concept of a mutex.

Usage in C#
This example shows how a local mutex object is used to synchronize access to a protected resource. Because each calling thread is blocked until it acquires ownership of the mutex, it must call the ReleaseMutex method to release ownership of the thread.

using System;
using System.Threading;

namespace MutexExampleConsoleApp1
{
    class Program
    {
        //Create a new Mutex. The creating thread does not own the mutex.
        private static Mutex mut = new Mutex();
        private const int numIterations = 1;
        private const int numThreads = 3;

        static void Main(string[] args)
        {
            //create the threads that will use the protected resource.
            for (int i = 0; i < numThreads; i++)
            {
                Thread newThread = new Thread(new ThreadStart(ThreadProc));
                newThread.Name = String.Format("Thread{0}", i + 1);
                newThread.Start();
            }

            // The main thread exits, but the application continues to run
            // until all foreground threads have exited.

            Console.ReadLine();
        }

        private static void ThreadProc()
        {
            for (int i = 0; i < numIterations; i++) {
                UseResource();    
            }
        }

        /// <summary>
        /// this method represents a resource that must be synchronized 
        /// so that only one thread at a time can enter.
        /// </summary>
        private static void UseResource()
        {
            //Wait until it is safe to enter
            Console.WriteLine("{0} is requesting the mutex", Thread.CurrentThread.Name);
            mut.WaitOne();

            Console.WriteLine("{0} has entered the protected area", Thread.CurrentThread.Name);
            //Place the code to access non-reentrant resouces here.

            //Simulate some work.
            Thread.Sleep(500);

            Console.WriteLine("{0} is leaving the protected area", Thread.CurrentThread.Name);

            //Release the Mutex.
            mut.ReleaseMutex();
            Console.WriteLine("{0} is released the mutex", Thread.CurrentThread.Name);
        }
    }
}

在这里插入图片描述
Synchronization serves two purposes:

  1. to ensure safety for updates on shared data(eg. to avoid races conditions),
    and 2) to coordinate and order actions taken by threads(e.g. handling threads which communicate intermediate results amongst one another).

Parallel programs is that all their possible interleaving must be correct. On possible way to guarantee this is to simply put one lock in the beginning of each thread; however, it is also clear that we want to use as few constraints as possible, in order to effectively exploit the available concurrency.
In general, locks provide safety and correctness, while condition variable provide ordering.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值