初学多线程(一)--保护共享资源
2016-01-26 21:23
281 查看
1.共享资源未被保护,被多个线程并行访问,会发生资源分配上的冲突,两种方法保护共享资源
ps:共享资源像静态类中的字段,方法
How to protect shared resources from concurrent access?
2.Interlocked类只能对int/long类型的字段addition/subtraction(increment , decrement ,add etc),这个类包含自增自减的方法,所以Interlocked.Increment(total),中total不用写成total++
ps:共享资源像静态类中的字段,方法
How to protect shared resources from concurrent access?
1.使用 Interlocked.Increment(字段) //在System.Threading class Program { static int total = 0; static void Main(string[] args) { Stopwatch sp = Stopwatch.StartNew(); Thread t1 = new Thread(AddToMillion); Thread t2 = new Thread(AddToMillion); Thread t3 = new Thread(AddToMillion); t1.Start(); t2.Start(); t3.Start(); t1.Join(); t2.Join(); t3.Join(); Console.WriteLine("the total = " + total .ToString ()); sp.Stop(); Console.WriteLine("ticks = "+sp.ElapsedTicks); } static void AddToMillion() { for (int i = 0; i < 1000000; i++) { Interlocked.Increment(total); } } } 运行结果:the total = 30000 ticks = 117078
2.使用lock对code session 进行锁定 //使用lock时要创建一个私有的静态object对象 // private static object obj = new object(); class Program { static int total = 0; static void Main(string[] args) { Stopwatch sp = Stopwatch.StartNew(); Thread t1 = new Thread(AddToMillion); Thread t2 = new Thread(AddToMillion); Thread t3 = new Thread(AddToMillion); t1.Start(); t2.Start(); t3.Start(); t1.Join(); t2.Join(); t3.Join(); Console.WriteLine("the total = " + total .ToString ()); sp.Stop(); Console.WriteLine("ticks = "+ sp.ElapsedTicks); } static object obj = new object(); static void AddToMillion() { for (int i = 0; i < 1000000; i++) { lock(obj ) { total++; } } } } 运行结果:total= 3000000 ticks = 334236
2.Interlocked类只能对int/long类型的字段addition/subtraction(increment , decrement ,add etc),这个类包含自增自减的方法,所以Interlocked.Increment(total),中total不用写成total++
相关文章推荐
- Top (参数)
- 两颗骰子
- js选项卡切换实战
- CSS竖排
- LightOJ1191 Bar Codes(DP)
- css代码结构
- 编程之美 - 爬楼梯问题
- LaTeX----表格处理
- 【Cocos2d-x】源码分析之 2d/ui/Widget
- awk模式处理语言
- HDOJ 4249 A Famous Equation DP
- 快速排序
- 老版本ubuntu 更新源
- Linux环境搭建
- tornado 使用supervisor管理进程,使用nginx做负载均衡
- shell & dialog
- JDBC向oracle插入数据
- Web前端——jsp页面参数显示的几个小问题
- js表格操作实践
- ubuntu防火墙设置