Synchronizing Access to Resources

本文介绍了多线程编程中资源同步访问的问题。文件系统在应用访问文件时会加锁,.NET提供同步对象解决此问题。阐述了需关注的四类资源,还介绍了Monitor类、ReaderWriterLock、Interlocked等实现资源同步的方式及代码示例,说明了Interlocked可避免多线程递增整数时的错误。

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

General speaking, file system will lock the file when an application is accessing it. If another application wana access this file, it must wait for the lock to be released. In multithreaded programming, we face the same situation. However, to make it easy, .NET provide synchronization object to help us to do this task. There are four types of resources that we need to pay attendtion:

-System resources, like communication ports
-Resources shared by multiple process, like file handles
-The resources of a single application domain accessed by multiple threads, like global, static, and instance fields
-Objects instances that are accessed by multiple threads.

Monitor Class: is applied to lock objects. In C#, using keword lock to specify the object that you want to monitor.
1 public void Subtract()
2 {
3     lock (this)
4     {
5         result = value1 - value2;
6         Thread.Sleep(1000);
7         Console.WriteLine("Subtract: " + result);
8     }
9 }

When a Thread.Start(Subtract()) is called, other functions cannot access value1, value2, and result due to Subtract() is accessing these varialbes. In other words, this lock behavior prevents result value from being overwritten. Nevertheless, Monitor class does not lock value type, but only lock the reference type. Therefore, Monitor locks the object to which Subtract() belongs, not the result variables itself.

However, Monitor class does not separate read and write lock. Multiple threads might need to read value simultaneously. If using Monitor class, only one thread can read a file at a time, another one has to wait.

ReaderWriterLock, allowes more than one threads read file at same time. And this would be stopped if a thread begin to write to this file. 
       
 1 class MemFile
 2 {
 3     string file = "Hello, world!";
 4     ReaderWriterLock rwl = new ReaderWriterLock();
 5     public void ReadFile()
 6     {
 7         // Allow thread to continue only if no other thread
 8         // has a write lock
 9         rwl.AcquireReaderLock(10000);
10         for (int i = 1; i <= 3; i++)
11         {
12         Console.WriteLine(file);
13         Thread.Sleep(1000);
14         }
15         rwl.ReleaseReaderLock();
16     }
17     public void WriteFile()
18     {
19         // Allow thread to continue only if no other thread
20         // has a read or write lock
21         rwl.AcquireWriterLock(10000);
22         file += " It's a nice day!";
23         rwl.ReleaseWriterLock();
24     }
25 }

Interlocked Performing atomic operations (are static methods) in thread-safe way, which is an alternative to locking access to a resource.
 1 int num = 0;
 2 //num += 1
 3 Interlocked.Increment(ref num);
 4 //num -=1;
 5 Interlocked.Decrement(ref num);
 6 //num += val2
 7 Interlocked.Add(ref num, 10);
 8 //Set the value of an object: num = 35
 9 Interlocked.Exchange(ref num, 35);
10 //if num == 75 then num = 35
11 Interlocked.CompareExchange(ref num, 7535);
12 //This is equivalent to reading a variable.
13 Interlocked.Read(ref num);

Increment an Integer in multithread application (2 threads) can cause some error if Interlocked.Increment() is not applied:
- Incrementing an Integer has 2 steps: 1, read the original value; 2, replace the value with newly incremented value.
- When Thread1 read the original value (i.e. 10) and then is interrupted by Thread2, Thread2 read the same original value (10) and replace with 11 (add 1).
- When Thread2 finished, Thread1 still process the original value as it was before Thread2 updated it, so it is still 10, and then rewrite the value with 11.
- Therefore, two threads cause only 1 increment, which is actually expected to cause 2 increments.

Using Interlocked.Increment(ref num) can avoid this error. Because it does not allow another thread to interrupt the increment operation.

转载于:https://www.cnblogs.com/thinkriver/archive/2009/08/19/1549770.html

一、综合实战—使用极轴追踪方式绘制信号灯 实战目标:利用对象捕捉追踪和极轴追踪功能创建信号灯图形 技术要点:结合两种追踪方式实现精确绘图,适用于工程制图中需要精确定位的场景 1. 切换至AutoCAD 操作步骤: 启动AutoCAD 2016软件 打开随书光盘中的素材文件 确认工作空间为"草图与注释"模式 2. 绘图设置 1)草图设置对话框 打开方式:通过"工具→绘图设置"菜单命令 功能定位:该对话框包含捕捉、追踪等核心绘图辅助功能设置 2)对象捕捉设置 关键配置: 启用对象捕捉(F3快捷键) 启用对象捕捉追踪(F11快捷键) 勾选端点、中心、圆心、象限点等常用捕捉模式 追踪原理:命令执行时悬停光标可显示追踪矢量,再次悬停可停止追踪 3)极轴追踪设置 参数设置: 启用极轴追踪功能 设置角度增量为45度 确认后退出对话框 3. 绘制信号灯 1)绘制圆形 执行命令:"绘图→圆→圆心、半径"命令 绘制过程: 使用对象捕捉追踪定位矩形中心作为圆心 输入半径值30并按Enter确认 通过象限点捕捉确保圆形位置准确 2)绘制直线 操作要点: 选择"绘图→直线"命令 捕捉矩形上边中点作为起点 捕捉圆的上象限点作为终点 按Enter结束当前直线命令 重复技巧: 按Enter可重复最近使用的直线命令 通过圆心捕捉和极轴追踪绘制放射状直线 最终形成完整的信号灯指示图案 3)完成绘制 验证要点: 检查所有直线是否准确连接圆心和象限点 确认极轴追踪的45度增量是否体现 保存绘图文件(快捷键Ctrl+S)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值