Introduction to Mutex

本文深入解析互斥锁(Mutex)的概念及其在防止竞态条件、同步多线程访问共享资源中的作用。通过生动的例子,如厕所钥匙和橡胶鸡,解释了互斥锁的工作原理,并提供了C#中使用互斥锁的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

内容概要:《2024年印尼税收袖珍指南》由普华永道发布,涵盖了印尼税收体系的关键方面。主要内容包括企业所得税、个人所得税、预提税、国际税收协定、增值税、奢侈品销售税、碳税、关税与消费税、税收优惠、地方税、印花税、税务会计、税务稽查与评估、强制执行征税、税务纠纷与处理等。企业所得税税率一般为22%,特定条件可享受优惠。个人所得税采用超额累进税率,最高达35%。预提税涵盖多种收入类型,如工资、利息、股息等。国际税收协定帮助避免双重征税,提供优惠税率。增值税标准税率为11%,部分商品和服务免征。税收优惠包括免税期、加计扣除等,尤其针对特定行业和地区。地方税种类繁多,如土地与建筑物税、机动车税等。税务稽查与评估确保纳税人合规,税务纠纷可通过异议、申诉、诉讼等方式解决。 适用人群:企业财务人员、税务顾问、跨国公司税务部门、个人纳税人等。 使用场景及目标:①帮助企业理解和遵守印尼税法,优化税务规划;②协助个人纳税人正确申报各类税项;③为税务顾问提供最新税收政策信息,提升专业服务水平;④为跨国公司处理跨境税务问题提供指导。 阅读建议:此指南内容详尽,建议读者根据自身需求重点阅读相关章节,结合实际案例深入理解各项规定,并关注最新政策动态,确保税务处理合法合规。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值