zoukankan      html  css  js  c++  java
  • 并发编程101

    AsParallel() 不适合io等待型程序,默认并行数是min(CPU数量,64)

    ConcurrentQueue 内部实现线程安全,显然当并发写或读会有性能损失在协调上。可以认为的错开这种时间,在不影响需求下。

    对于Queue的问题:

    如果初始化的时候没有传入capcity,然后又极快(多线程并发入队)的入队元素那么会抛出长度不够的异常

    编译器是Release下时

    未经处理的异常:  System.AggregateException: 发生一个或多个错误。 ---> System.Arg
    umentException: 目标数组的长度不够。请检查 destIndex 和长度以及数组的下限。
       在 System.Array.Copy(Array sourceArray, Int32 sourceIndex, Array destinationA
    rray, Int32 destinationIndex, Int32 length, Boolean reliable)
       在 System.Collections.Generic.Queue`1.SetCapacity(Int32 capacity)
       在 System.Collections.Generic.Queue`1.Enqueue(T item)

    Best Practices
    • All code you write should rely only on the guarantees made by the ECMA C# specification, and not on any of the implementation details explained in this article.
    • Avoid unnecessary use of volatile fields. Most of the time, locks or concurrent collections (System.Collections.Concurrent.*) are more appropriate for exchanging data between threads. In some cases, volatile fields can be used to optimize concurrent code, but you should use performance measurements to validate that the benefit outweighs the extra complexity.
    • Instead of implementing the lazy initialization pattern yourself using a volatile field, use the System.Lazy<T> and System.Threading.LazyInitializer types.
    • Avoid polling loops. Often, you can use a BlockingCollection<T>, Monitor.Wait/Pulse, events or asynchronous programming instead of a polling loop.
    • Whenever possible, use the standard .NET concurrency primitives instead of implementing equivalent functionality yourself.


     

    Barrier 类

    使多个任务能够采用并行方式依据某种算法在多个阶段中协同工作。

     

     

    典型的Volatile应用场景

    class Foo
    {
    int _answer;
    bool _complete;
    void A()
    {
    _answer = 123;
    _complete = true;
    }
    void B()
    {
    if (_complete) Console.WriteLine (_answer);
    }
    }

    If methods A and B ran concurrently on different threads, might it be possible for B to write “0”? The answer is yes—for
    the following reasons:
    · The compiler, CLR, or CPU may reorder your program's instructions to improve efficiency.
    · The compiler, CLR, or CPU may introduce caching optimizations such that assignments to variables won't be
    visible to other threads right away.

    罪魁祸首是编译器的优化,所以写额外代码取消优化。

    you must explicitly defeat these
    optimizations by creating memory barriers (also called memory fences) to limit the effects of

    1. instruction reordering
    2.read/write caching.

    解决方案:

    Full fences
    The simplest kind of memory barrier is a full memory barrier (full fence) which prevents any kind of

    instruction reordering

    or caching

    around that fence.Calling Thread.MemoryBarrier generates a full fence; we can fix our
    example by applying four full fences as follows:
    class Foo
    {
    int _answer;
    bool _complete;
    void A()
    {
    _answer = 123;
    Thread.MemoryBarrier(); // Barrier 1
    _complete = true;
    Thread.MemoryBarrier(); // Barrier 2
    }
    void B()
    {
    Thread.MemoryBarrier(); // Barrier 3
    if (_complete)
    {
    Thread.MemoryBarrier(); // Barrier 4
    Console.WriteLine (_answer);
    }
    }
    }

    备注


    只有在弱顺序多处理器系统(例如,使用多个 Intel Itanium 处理器的系统)上 MemoryBarrier 才是必需的。

    在大多数情况下,C# 中的 lock 语句、Visual Basic 中的 SyncLock 语句或 Monitor 类提供了更简单的方式来同步数据。

    消耗时间

    Remember that acquiring and releasing an uncontended
    lock takes as little as 20ns on a 2010-era desktop.

    A full fence takes around ten nanoseconds on a 2010-era desktop.

    让线程绑定到CPU上执行


    通过调用SetThreadAffinityMask,就能为各个线程设置亲缘性屏蔽:
    DWORD_PTR  SetThreadAffinityMask  (
    HANDLE  hThread,  //  handle  to  thread
    DWORD_PTR  dwThreadAffinityMask  //  thread  affinity  mask
    );

    Thread.Yield()

    在代码的任何位置插入,如果会让程序出错则说明程序存在BUG

    WINDOWS下切换线程时间

    Under Windows, a time-slice is typically in the tens-ofmilliseconds
    region—much larger than the CPU overhead in
    actually switching context between one thread and another (which
    is typically in the few-microseconds region).

    线程共享堆内存,方便数据交互

    threads share (heap) memory with other threads running in the same application.

    lambda表达式遇上异步的时候慎用!

    eg1:

    problem :

    for (int i = 0; i < 10; i++)
        new Thread (() => Console.Write (i)).Start();
    The output is nondeterministic! Here’s a typical result:
    0223557799

    solution:

    for (int i = 0; i < 10; i++)
    {
        int temp = i;
        new Thread (() => Console.Write (temp)).Start();
    }

    eg2:

    string text = "t1";
    Thread t1 = new Thread ( () => Console.WriteLine (text) );
    text = "t2";
    Thread t2 = new Thread ( () => Console.WriteLine (text) );
    t1.Start();
    t2.Start();
    Because both lambda expressions capture the same text variable, t2 is printed twice:
    t2
    t2

    为线程设置名字可能会帮助调试.

    线程的前台/后台状态,与其优先级或分配的执行时间没有关系。

    提升线程优先级后还是不够的话,需要再提进程优先级.

    进程间共享数据可以利用

    communicating via Remoting or memory-mapped files

    (Memory-mapped files)http://msdn.microsoft.com/zh-cn/library/ms810613.aspx

    操作系统中Kernel Mode和User Mode的区别

    为了不让程序任意存取资源,大部分的CPU架构都支持Kernel mode与User mode两种执行模式。当CPU运行于Kernel mode时,任务可以执行特权级指令,对任何I/O设备有全部的访问权,还能够访问任何虚拟地址和控制虚拟内存硬件;这种模式对应x86的ring0层,操作系统的核心部分,包括设备驱动程序都运行在该模式。当CPU运行于User Mode时,硬件防止特权指令的执行,并对内存和I/O空间的访问操作进行检查,如果运行的代码不能通过操作系统的某种门机制,就不能进入内核模式;这种模式对应于x86的

    ring3层,操作系统的用户接口部分以及所有的用户应用程序都运行在该级别。

    The Condition Variable Pattern

    表达式复杂时,表达式的求值不是原子的

    使用内存映射文件与只用文件流缓冲哪个更高效?

    openvas里面写文件使用了锁。。。

    线程池设置最小线程的MSDN警告说明警告

            您可以使用 SetMinThreads 方法增加线程的最小数量。但是,在不必要的情况下增加这些值,可能会导致性能问题。如果同时启动的任务过多则所有任务的处理速度看起来都可能很慢。大多数情况下,线程池使用自己的分配线程的算法将能够更好地工作。将空闲线程数的最小值减少到小于处理器的数目也会影响性能。

  • 相关阅读:
    JavaScript判断图片是否加载完成的三种方式 (转)
    支付宝异步通知notify_url接收不了问题解决(转)
    支付宝接口使用文档说明 支付宝异步通知(notify_url)与return_url
    Nginx Cache中$request_filename(转)
    win7下搭建nginx+php的开发环境(转)
    Nginx报出504 Gateway Timeout错误2
    BZOJ 3990 [SDOI 2015] 排序 解题报告
    BZOJ 3992 [SDOI 2015] 序列统计 解题报告
    BZOJ 3993 [SDOI 2015] 星际战争 解题报告
    BZOJ 3971 Матрёшка 解题报告
  • 原文地址:https://www.cnblogs.com/jiangzhen/p/2932434.html
Copyright © 2011-2022 走看看