当前位置: 首页 > news >正文

C#对线程同步的应用

什么是线程同步?线程同步的应用场景有哪些?在C#中有哪些线程同步方式?下面对这些问题做一个总结,让大家在面试的时候遇到这些问题能够游刃有余。
线程同步是指在多线程环境下,多个线程同时访问共享资源时,确保数据一致性和正确性的一种机制。以下是线程同步的主要应用场景和常用方式,以及每种方式的简单代码示例。


应用场景

  1. 共享资源的保护
  • 多个线程同时读写共享资源时,防止数据竞争和不一致。
  1. 线程间的通信
  • 一个线程等待另一个线程完成某些任务或传递数据。
  1. 避免死锁
  • 多线程并发访问资源时,通过合理设计同步机制,避免资源争用导致的死锁。
  1. 线程协调
  • 控制线程的执行顺序或实现生产者-消费者模式。

线程同步方式与示例

  1. 锁(lock / Monitor)
    用于同步对共享资源的访问,确保同时只有一个线程可以访问资源。
class Program
{private static readonly object _lock = new object();private static int _counter = 0;static void Main(){Thread t1 = new Thread(IncrementCounter);Thread t2 = new Thread(IncrementCounter);t1.Start();t2.Start();t1.Join();t2.Join();Console.WriteLine($"Final Counter: {_counter}");}static void IncrementCounter(){for (int i = 0; i < 1000; i++){lock (_lock){_counter++;}}}
}

  1. 信号量(Semaphore / SemaphoreSlim)
    用于限制对某些资源的访问线程数。
class Program
{private static SemaphoreSlim _semaphore = new SemaphoreSlim(2);static void Main(){for (int i = 1; i <= 5; i++){int id = i;new Thread(() => AccessResource(id)).Start();}}static void AccessResource(int id){Console.WriteLine($"Thread {id} is waiting to enter...");_semaphore.Wait();Console.WriteLine($"Thread {id} entered.");Thread.Sleep(2000); // Simulating workConsole.WriteLine($"Thread {id} is leaving.");_semaphore.Release();}
}

  1. 互斥(Mutex)
    用于跨进程同步资源。
class Program
{private static Mutex _mutex = new Mutex();static void Main(){for (int i = 1; i <= 3; i++){new Thread(AccessResource).Start(i);}}static void AccessResource(object id){Console.WriteLine($"Thread {id} waiting for mutex...");_mutex.WaitOne();Console.WriteLine($"Thread {id} acquired mutex.");Thread.Sleep(2000);Console.WriteLine($"Thread {id} releasing mutex.");_mutex.ReleaseMutex();}
}
  1. 手动重置事件(ManualResetEvent)
    允许一个线程通知其他线程可以继续。
class Program
{private static ManualResetEvent _mre = new ManualResetEvent(false);static void Main(){new Thread(WaitForSignal).Start();Console.WriteLine("Main thread doing work...");Thread.Sleep(2000);Console.WriteLine("Signal other threads to proceed.");_mre.Set();}static void WaitForSignal(){Console.WriteLine("Thread waiting for signal...");_mre.WaitOne();Console.WriteLine("Thread received signal!");}
}

  1. 自动重置事件(AutoResetEvent)
    每次调用 Set 后,自动重置为非信号状态。
class Program
{private static AutoResetEvent _are = new AutoResetEvent(false);static void Main(){new Thread(WaitForSignal).Start();Console.WriteLine("Main thread doing work...");Thread.Sleep(2000);Console.WriteLine("Signal other thread to proceed.");_are.Set();}static void WaitForSignal(){Console.WriteLine("Thread waiting for signal...");_are.WaitOne();Console.WriteLine("Thread received signal!");}
}

  1. 信号量栅栏(Barrier)
    允许多个线程到达某个同步点后再继续执行。
class Program
{private static Barrier _barrier = new Barrier(3, b => Console.WriteLine("All threads reached barrier."));static void Main(){for (int i = 1; i <= 3; i++){new Thread(Work).Start(i);}}static void Work(object id){Console.WriteLine($"Thread {id} doing work...");Thread.Sleep(new Random().Next(1000, 3000));Console.WriteLine($"Thread {id} waiting at barrier.");_barrier.SignalAndWait();Console.WriteLine($"Thread {id} passed barrier.");}
}

  1. 读写锁(ReaderWriterLockSlim)
    提供多个线程的读操作,但写操作是互斥的。
class Program
{private static ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();private static List<int> _data = new List<int>();static void Main(){new Thread(ReadData).Start();new Thread(WriteData).Start();}static void ReadData(){_lock.EnterReadLock();try{Console.WriteLine($"Read thread reading data: {string.Join(", ", _data)}");}finally{_lock.ExitReadLock();}}static void WriteData(){_lock.EnterWriteLock();try{_data.Add(new Random().Next(100));Console.WriteLine("Write thread updated data.");}finally{_lock.ExitWriteLock();}}
}

以上是常用的线程同步方式及其简单示例代码,您可以根据具体需求选择合适的方式来保证线程安全。希望对大家有所帮助。


http://www.lryc.cn/news/514512.html

相关文章:

  • 基于微信小程序的面部动作检测系统
  • Activation Functions
  • 《Vue3实战教程》37:Vue3生产部署
  • Linux:各发行版及其包管理工具
  • 【计算机网络】课程 作业一 搭建连续覆盖的办公网络
  • C++ 设计模式:单例模式(Singleton Pattern)
  • OpenCV调整图像亮度和对比度
  • Kafka Offset explorer使用
  • 二维码文件在线管理系统-收费版
  • UE4.27 Android环境下获取手机电量
  • vue-i18n报错
  • Docker新手:在tencent云上实现Python服务打包到容器
  • React基础知识学习
  • ES IK分词器插件
  • 二十三种设计模式-抽象工厂模式
  • python opencv的orb特征检测(Oriented FAST and Rotated BRIEF)
  • 高阶数据结构----布隆过滤器和位图
  • VScode使用密钥进行ssh连接服务器方法
  • 艾体宝产品丨加速开发:Redis 首款 VS Code 扩展上线!
  • 应用架构模式
  • 注入少量可学习的向量参数: 注入适配器IA3
  • 【C++】B2076 球弹跳高度的计算
  • 【Python】selenium结合js模拟鼠标点击、拦截弹窗、鼠标悬停方法汇总(使用 execute_script 执行点击的方法)
  • CatBoost算法详解与PyTorch实现
  • “TypeScript版:数据结构与算法-初识算法“
  • mysql中递归的使用 WITH RECURSIVE
  • 点击取消按钮,console出来数据更改了,页面视图没有更新
  • web框架在什么程度上受限 ?
  • 实践:事件循环
  • C++ 设计模式:建造者模式(Builder Pattern)