多线程共享变量的原子操作(Interlocked 类)

本文深入解析Interlocked类,展示如何在多线程环境下对共享变量进行原子操作,避免竞态条件,确保线程安全。通过具体示例代码,演示了Interlocked.Exchange方法的使用,实现资源的线程安全锁定。

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

Inrerlocked类介绍
官方文档:https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.interlocked?redirectedfrom=MSDN&view=netframework-4.8

本文主要介绍如何使用Inrerlocked来对多线程中共享变量的原子操作。

官方文档及示例已经介绍很清楚,不做过多描述


Interlocked 类

命名空间:System.Threading

程序集:System.Threading.dll, mscorlib.dll, netstandard.dll

为多个线程共享的变量提供原子操作。

public static class Interlocked

继承
Object->Interlocked

示例
下面的代码示例演示线程安全资源锁定机制。

using System;
using System.Threading;

namespace InterlockedExchange_Example
{
    class MyInterlockedExchangeExampleClass
    {
        //0 for false, 1 for true.
        private static int usingResource = 0;

        private const int numThreadIterations = 5;
        private const int numThreads = 10;

        static void Main()
        {
            Thread myThread;
            Random rnd = new Random();

            for(int i = 0; i < numThreads; i++)
            {
                myThread = new Thread(new ThreadStart(MyThreadProc));
                myThread.Name = String.Format("Thread{0}", i + 1);
            
                //Wait a random amount of time before starting next thread.
                Thread.Sleep(rnd.Next(0, 1000));
                myThread.Start();
            }
        }

        private static void MyThreadProc()
        {
            for(int i = 0; i < numThreadIterations; i++)
            {
                UseResource();
            
                //Wait 1 second before next attempt.
                Thread.Sleep(1000);
            }
        }

        //A simple method that denies reentrancy.
        static bool UseResource()
        {
            //0 indicates that the method is not in use.
            if(0 == Interlocked.Exchange(ref usingResource, 1))
            {
                Console.WriteLine("{0} acquired the lock", Thread.CurrentThread.Name);
            
                //Code to access a resource that is not thread safe would go here.
            
                //Simulate some work
                Thread.Sleep(500);

                Console.WriteLine("{0} exiting lock", Thread.CurrentThread.Name);
            
                //Release the lock
                Interlocked.Exchange(ref usingResource, 0);
                return true;
            }
            else
            {
                Console.WriteLine("   {0} was denied the lock", Thread.CurrentThread.Name);
                return false;
            }
        }

    }
}

/*
输出:
Thread1 acquired the lock
   Thread2 was denied the lock
Thread1 exiting lock
Thread3 acquired the lock
   Thread2 was denied the lock
   Thread1 was denied the lock
Thread3 exiting lock
Thread4 acquired the lock
   Thread5 was denied the lock
Thread4 exiting lock
   Thread6 was denied the lock
Thread2 acquired the lock
   Thread1 was denied the lock
   Thread3 was denied the lock
   Thread7 was denied the lock
   Thread8 was denied the lock
   Thread5 was denied the lock
   Thread9 was denied the lock
Thread2 exiting lock
Thread10 acquired the lock
   Thread4 was denied the lock
   Thread6 was denied the lock
Thread10 exiting lock
Thread1 acquired the lock
   Thread3 was denied the lock
   Thread7 was denied the lock
   Thread8 was denied the lock
   Thread5 was denied the lock
   Thread9 was denied the lock
   Thread2 was denied the lock
Thread1 exiting lock
Thread4 acquired the lock
   Thread6 was denied the lock
   Thread10 was denied the lock
   Thread3 was denied the lock
Thread4 exiting lock
Thread7 acquired the lock
   Thread5 was denied the lock
   Thread8 was denied the lock
   Thread9 was denied the lock
   Thread2 was denied the lock
   Thread1 was denied the lock
   Thread6 was denied the lock
Thread7 exiting lock
Thread10 acquired the lock
   Thread3 was denied the lock
   Thread4 was denied the lock
   Thread5 was denied the lock
   Thread8 was denied the lock
   Thread9 was denied the lock
Thread10 exiting lock
Thread6 acquired the lock
   Thread7 was denied the lock
   Thread4 was denied the lock
Thread6 exiting lock
Thread8 acquired the lock
   Thread9 was denied the lock
   Thread10 was denied the lock
   Thread7 was denied the lock
Thread8 exiting lock
Thread10 acquired the lock
Thread10 exiting lock

*/

注解

此类的方法可帮助防止在以下情况下发生的错误:在以下情况下发生:计划程序在以下情况下切换上下文:当线程正在更新可被其他线程访问的变量时,或当两个线程同时在不同的处理器上执行时。 此类的成员不会引发异常。

方法

Exchange(Int32, Int32)
以原子操作的形式,将 32 位有符号整数设置为指定的值并返回原始值。

dengdengdeng…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值