美文网首页编程程序员
《七天七并发》笔记第一天互斥和内存模型

《七天七并发》笔记第一天互斥和内存模型

作者: 铁眉 | 来源:发表于2016-03-18 00:29 被阅读258次

    《七天七并发》第一天互斥和内存模型

    • 并行并不只是说多核

      • bit level 并行
      • intstruction-level并行。通过流水线、乱序执行、猜测执行达到
      • data-level并行。并行对大量数据施加统一操作,如GPU
      • task-level。多处理器
    • 并发问题产生原因:

      • 内存可见性问题。
      • 指令乱序执行。编译器静态优化、JVM动态优化、硬件乱序来优化性能。++i 解释成多个指令,加重了乱序的影响。
    • synchronization:执行顺序上(互斥)、可见性上的双重保证。即happens before的语义:

      • Each action in a thread happens before every action in that thread that comes later in the program's order.
      • An unlock on a monitor happens before every subsequent lock on that same monitor.
      • A write to a volatile field happens before every subsequent read of that same volatile.
      • A call to start() on a thread happens before any actions in the started thread.
      • All actions in a thread happen before any other thread successfully returns from a join() on that thread.
    • 只涉及一个变量的互斥场景,使用java.util.concurrent.aotmic包是好选择。

    • Thread.join方法使得检查线程是否已终止,并将其他线程对共享内存的修改对当前线程可见。

    • 【哲学家就餐问题】https://zh.wikipedia.org/wiki/%E5%93%B2%E5%AD%A6%E5%AE%B6%E5%B0%B1%E9%A4%90%E9%97%AE%E9%A2%98

      • 【资源分级解法】将争用的资源编号,获取时编号从小到大,释放时编号从大到小。如果已获取资源3,5,要去获取资源2,那么必须先释放资源5,3。原理是:只有持有最大编号资源的一个哲学家可以进餐,而他不会卡死,因为他之所以能获取最大编号资源,是因为所需小编号资源已经被持有了。这样就能保证至少有一个哲学家可以进餐。
      • 【服务生解法】通过一个服务生(master thread)原子性打包分配所需资源,保证了资源获取的串行。
      • 【Chandy/Misra解法】将筷子凑成对(资源打包),饿的人将获得一个换筷子券,饿的人将券给有筷子的人,有筷子的人吃完了,将筷子给刚才给券的人。原理是,多个资源打包,资源获取、释放都是原子性的。
      • 哲学家思考时间越一致,比如都不思考,一直在争用资源,越容易死锁。哲学家就餐时间越长,越容易死锁。
    • 【incorrectly synchronized】即【 data race】:

      • there is a write of a variable by one thread,
      • there is a read of the same variable by another thread and
      • the write and read are not ordered by synchronization
    • 内置锁限制:

      • 进入阻塞后无法中断
      • 无法设置超时
      • 代码块只能在同一个方法中

    java内存模型

    《The Java Memory Model》http://www.cs.umd.edu/~pugh/java/memoryModel/

    界定了这些并发问题的界限,并给出解决方案。

    final

    int old memory model. synchronization was the only way to ensure that all threads see the value of a final field that was written by the constructor.
    新的JMM中,只要constructor过程中this不逸出,则能保证final字段被其他线程正确的看到,如果final字段指向一个数组或对象,数组或对象,也能保证其他线程看到构造器结束那个点的最新的值,而不是现在最新的值(因为构造完成后,有可能先被其他线程更新了)。

    volatile

    Under the old memory model, accesses to volatile variables could not be reordered with each other, but they could be reordered with nonvolatile variable accesses. 这样会导致volatile不能作为两个线程之间的信号变量,因为线程B看到volatile的变量变更后,不能保证在线程A中排在该volatile变量之前的write能被看到。
    于是volatile变量似乎有了锁的作用:Writing to a volatile field has the same memory effect as a monitor release, and reading from a volatile field has the same memory effect as a monitor acquire.
    In effect, because the new memory model places stricter constraints on reordering of volatile field accesses with other field accesses, volatile or not, anything that was visible to thread A when it writes to volatile field f becomes visible to thread B when it reads f.
    因此volatile只能保证可见性问题,没法保证互斥问题。

    volatile很实用于开关场景,比如标识一件事做完了,比如初始化完成了,或者网络请求处理完成。

    "double-checked locking" problem

    为了lazy init,某个field被使用时候才init。

    class SomeClass {
      private Resource resource = null;
      public Resource getResource() {
        if (resource == null) {
          synchronized {
            if (resource == null) 
              resource = new Resource();
          }
        }
        return resource;
      }
    }
    

    因为可能在Resource构造完成之前,它的引用就被赋给SomeClass的field resource。所以线程B可能看到被初始化了一般的Resource对象。
    The class loader, which synchronizes on the classes' Class object, executes static initializer blocks at class initialization time. That means that the effect of static initializers is automatically visible to all threads as soon as the class loads.

    【解决方案一】:
    static filed的初始化已经基于这个class的class obj synchronizes过了,所以一旦初始化完成能理解被其他thread看到:
    The class loader, which synchronizes on the classes' Class object, executes static initializer blocks at class initialization time. That means that the effect of static initializers is automatically visible to all threads as soon as the class loads.
    基于这个,另外为了保证lazy load,可以这么做:
    When the initialized object is a static field of a class with no other methods or fields, the JVM effectively performs lazy initialization automatically.

    【解决方案二】:在JSR133标准实施后(>= jdk1.5),可以通过将resource申明为violate解决这个问题。

    相关文章

      网友评论

        本文标题:《七天七并发》笔记第一天互斥和内存模型

        本文链接:https://www.haomeiwen.com/subject/rficlttx.html