多线程 并发编程与异步方法

来源:互联网 发布:淘宝退货多久自动退款 编辑:程序博客网 时间:2024/05/22 05:07

1. Parallel Programming中的PLINQ, Parallel Class与Task Parallelism的特点?

    并发编程的内容类似于Google的Map-Reduce的算法。多线程的着眼点是线程的互斥,同步等。而并行编程的着眼点是如何提高多个CPU利用率。书中描述了未来的景象,PC机有32个内核。这个在Server中估计已经是现实了。而宏观的例如Map-Reduce不仅仅是CPU Cores之间的并发,更是成千上万个计算机之间的并发。这属于分布式计算的范畴了。这里讨论的也就是C# 4.0中的这些并发计算的概念依旧是如何将任务分解成Work Items以便充分应用所有的内核。这是Parallel Programming和Multi Thread之间的主要区别。

     服务器端与桌面开发:

     服务器端面临的主要问题是高并发,需要确保用户响应时间,采用的方法是多线程。面临两个瓶颈,一是thread的创建与销毁,二是现场的保护与恢复。

     解决第一个问题采用的是ThreadPool或者Asynchronous Programming。解决第二个问题是合理设置线程的数量。

     桌面端采用UI 线程和Background 线程结合的方式,也是要确保用户响应时间。

2.关于多线程

   关于多线程的同步,互斥等的机制及其实现在实际应用中有一定的困难,尤其是debug。但是当OO与多线程结合时线程用到的数据需要特别注意。"You need to be alsolutely clear in you head on where the infomation you're working with live, where it came from, and whether other threads might be able to see it."。

To summarize: infomation that really does live on the stack is private to a particular thread. Unfortuately, using local variables doesn't necessarily guarantee that the state you're working with is on the stack. Be wary of reference types-no matter where the reference lives, the thing it refers to will not be on the stack, so you need to understand what other code might have a reference to the object you're using.

 有两类阐述的模式,一类告诉你是什么,一类告诉你它的背景,意图以及所适用的范围。例如SpinLock与Lock的区别。SpinLock用了问询的方式目的是避免使用OS的scheduler。目的相同但采用不同的手段就意味着它各有其适用的场景。SplinLock就适合contention很少或者竞争的线程执行的时间很短的情况。

3. Asynchronous Delegate VS Asynchronous Method

  • Asynchronous delegate 使用的是BeginInvoke and EndInvoke;
  • Asynchronous method 使用的是BeginXXX and EndXXX. 例如File.BeginRead;

4. 应用Thread Pool的几种情况:

  •  Task Parallel Library or PLINQ
  •  ThreadPool.QueueUserWorkItem      
  •  Asynchronous delegate
  •  BackgroundWorker

   注意: Task 是QueueUserWorkItem的替代者。Task<TResult>是Asynchronous delegate的替代者

   TPL中的Error Handling:

    TPL设法确保程序没有忽略异常,所以TPL中的异常必须处理。

  •  采用ContinueWith;
  • Try ...  Catch;

5. ThreadPool.QueueUserWorkItem 与 Asynchronous delegate的区别

  • Asynchronous delegate可以从线程返回数据;
  • Asynchronous delegate可以接收任意数量及类型的参数;
  • Asynchronous delegate可以返回异常到调用者;

6. Synchronization

  • Simple Blocking: Wait, Sleep, Join
  • Locking:  独占锁: lock(Monitor.Enter/Monitor.Exit),  Mutex, SpinLock; 非独占锁: Semaphore, SemaphoreSlim, ReaderWriterLockSlim.
  • Signaling:  Event wait handle(AutoResetEvent/ManualResetEvent),  Monitor.Wait/Monitor.Pulse,  CountdownEvent,  Barrier.
  • Nonblocking Synchronization:  Thread.MemoryBarrier, Thread.VolatileRead, Thread.VolatileWrite, volatile, Interlocked