首页 > 代码库 > 读写锁学习(2)——ReaderWriterLock学习
读写锁学习(2)——ReaderWriterLock学习
using System.Collections.Generic;using System.Threading;namespace FYSTest{ public partial class MainWindow { List<int> list = new List<int>(); private ReaderWriterLock _rwlock = new ReaderWriterLock(); public MainWindow() { //InitializeComponent(); Thread ThRead = new Thread(new ThreadStart(Read)); ThRead.IsBackground = true; Thread ThRead2 = new Thread(new ThreadStart(Read)); ThRead2.IsBackground = true; Thread ThWrite = new Thread(new ThreadStart(Write)); ThWrite.IsBackground = true; ThRead.Start(); ThRead2.Start(); ThWrite.Start(); } private void Read() { while (true) { //使用一个 System.Int32 超时值获取读线程锁。 _rwlock.AcquireReaderLock(100); try { if (list.Count > 0) { int result = list[list.Count - 1]; } } finally { //减少锁计数,释放锁 _rwlock.ReleaseReaderLock(); } } } int WriteCount = 0;//写次数 private void Write() { while (true) { //使用一个 System.Int32 超时值获取写线程锁。 _rwlock.AcquireWriterLock(100); try { list.Add(WriteCount++); } finally { //减少写线程锁上的锁计数,释放写锁 _rwlock.ReleaseWriterLock(); } } } }}
读写锁学习(2)——ReaderWriterLock学习
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。