Chinaunix首页 | 论坛 | 博客
  • 博客访问: 12398370
  • 博文数量: 1293
  • 博客积分: 13501
  • 博客等级: 上将
  • 技术积分: 17974
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-08 18:11
文章分类

全部博文(1293)

文章存档

2019年(1)

2018年(1)

2016年(118)

2015年(257)

2014年(128)

2013年(222)

2012年(229)

2011年(337)

分类: C#/.net

2013-03-30 10:58:33

一、多线程入的好处

    在应用程序中使用多个线程的好处是每个线程都可以异步执行。对于Windows应用程序,耗时的任务可以在后台执行,而使应用程序的窗口和控件保持响应。对于服务器应用程序,多线程处理提供了用不同线程处理每个传入请求的能力。否则,在完全满足前一个请求之前,将无法处理每个新请求。


二、多线程带来的并发问题

    然而,线程的异步特性意味着必须协调对资源(如文件句柄、网络连接和内存)的访问、即必须确保任何共享数据都处于被保护状态。否则,两个或更多的线程可能在同一时间访问相同的资源,而每个线程都不知道其他线程的操作。结果将产生不可预知的数据损坏。

案例测试代码:


  1. namespace MultiThreadPrint
  2. {
  3.     public class CPrinter
  4.     {
  5.         public void PrintNumbers()
  6.         {
  7.             Console.WriteLine("{0} is excuting PrintNumbers()", Thread.CurrentThread.Name);
  8.             for (int i = 0; i < 10; i++)
  9.             {
  10.                 Random r = new Random();
  11.                 Thread.Sleep(1000 * r.Next(5));
  12.                 Console.Write("{0}, ", i);
  13.             }
  14.             Console.WriteLine();
  15.         }
  16.     };
  17.     class Program
  18.     {
  19.         static void Main(string[] args)
  20.         {
  21.             CPrinter p = new CPrinter();
  22.             // Thread threads[] = new Thread[10]; /* Note that this is the wrong way. */
  23.             Thread[] threads = new Thread[10]; // This is create array,not concrete thread.
  24.             for (int i = 0; i < 10; i++)
  25.             {
  26.                 threads[i] = new Thread(new ThreadStart(p.PrintNumbers));
  27.                 threads[i].Name = "Worker thread #" + i.ToString();
  28.             }
  29.             foreach (Thread t in threads)
  30.             {
  31.                 t.Start();
  32.             }
  33.             Console.ReadLine();
  34.         }
  35.     }
  36. }


image图1

    由图1可以看出,十个线程共享一个CPrinter对象时,输出的数据并不是“0,1,2,3,4,5,6,7,8,9”这样有规律的输出,而是出现了各个数据的穿插。说明有某一个时间片线程A调用了CPrinter的PrintNumbers(),别一个时间片线程B也调用了CPrinter的PrintNumbers(),很明显线程A的循环并没有完全执行。而CPrinter对象在各个不同线程的相互竞争中所以打印出了这图1的没规律数据。

 

三、实现数据同步的相关方法

    对于整数数据类型简单操作,可以用Interlocked类的成员来实现线程同步。对于其他所有数据类型和非线程安全的资源,需要使用lock\mutex等机制来处理,详情后解。下面给出Interlocked的案例。


  1. namespace InterlockedHandle
  2. {
  3.     class Program
  4.     {
  5.         //0 for false, 1 for true.
  6.         private static int usingResource = 0;
  7.         private static Object currentMso;
  8.         private static Object globalMso = new Object();
  9.         private const int numThreadIterations = 5;
  10.         private const int numThreads = 10;
  11.         static void Main()
  12.         {
  13.             Thread myThread;
  14.             Random rnd = new Random();
  15.             for (int i = 0; i < numThreads; i++)
  16.             {
  17.                 myThread = new Thread(new ThreadStart(MyThreadProc));
  18.                 myThread.Name = String.Format("Thread{0}", i + 1);
  19.                 //Wait a random amount of time before starting next thread.
  20.                 Thread.Sleep(rnd.Next(0, 1000));
  21.                 myThread.Start();
  22.             }
  23.             Console.ReadLine();
  24.         }
  25.         private static void MyThreadProc()
  26.         {
  27.             for (int i = 0; i < numThreadIterations; i++)
  28.             {
  29.                 UseResource();
  30.                 //Wait 1 second before next attempt.
  31.                 Thread.Sleep(1000);
  32.             }
  33.         }
  34.         //A simple method that denies reentrancy.
  35.         static bool UseResource()
  36.         {
  37.             //0 indicates that the method is not in use.
  38.             if (0 == Interlocked.Exchange(ref usingResource, 1))
  39.             {
  40.                 Console.WriteLine("{0} acquired the lock", Thread.CurrentThread.Name);
  41.                 //Code to access a resource that is not thread safe would go here.
  42.                 //Simulate some work
  43.                 Thread.Sleep(500);
  44.                 Console.WriteLine("{0} exiting lock", Thread.CurrentThread.Name);
  45.                 //Release the lock
  46.                 Interlocked.Exchange(ref usingResource, 0);
  47.                 return true;
  48.             }
  49.             else
  50.             {
  51.                 Console.WriteLine(" {0} was denied the lock", Thread.CurrentThread.Name);
  52.                 return false;
  53.             }
  54.         }
  55.     }
  56. }



image图2

    图2可以看到usingResource 作为一个整型数据类型,当多个线程想对异步其进行访问时,因为这存在数据的同步问题。这里使用了Interlocked来使用每个线程要想访问usingResource,必须等待别一个线程使用完退出后才行!这样保证了数据的安全。

 

参考文献

MSDN--Interlocked 类

《C#与.NET4高级程序设计(第5版)》

阅读(2765) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~