zoukankan      html  css  js  c++  java
  • iOS并发编程指南之同步

    1.gcd

    fmdb使用了gcd,它是通过 建立系列化的G-C-D队列 从多线程同时调用调用方法,GCD也会按它接收的块的顺序来执行。

    fmdb使用的是dispatch_sync,多线程调用a serialized queue,gcd会在接收块的线程执行,并阻塞其他线程

    使用FMDatabaseQueue 及线程安全
    在多个 线程中同时使用一个FMDatabase实例是不明智的。现在你可以为每个线程创建一个FMDatabase对象。 不要让多个线程分享同一个实例,它无法在多个线程中同时使用。 若此,坏事会经常发生,程序会时不时崩溃,或者报告异常,或者陨石会从天空中掉下来砸到你Mac Pro.  总之很崩溃。所以,不要初始化FMDatabase对象,然后在多个线程中使用。请使用 FMDatabaseQueue,它是你的朋友而且会帮助你。以下是使用方法:
     
    FMDatabaseQueue  后台会建立系列化的G-C-D队列,并执行你传给G-C-D队列的块。这意味着 你从多线程同时调用调用方法,GDC也会按它接收的块的顺序来执行。谁也不会吵到谁的脚 ,每个人都幸福。

    Although you should add tasks asynchronously whenever possible, there may still be times when you need to add a task synchronously to prevent race conditions or other synchronization errors. In these instances, you can use the dispatch_sync and dispatch_sync_f functions to add the task to the queue. These functions block the current thread of execution until the specified task finishes executing.

    这和传统的线程很相似。在《unix network programming volume 2》中,介绍了大量的同步方法。

    Part 3. Synchronization
    7. Mutexes and Condition Variables
    8. Read-Write Locks
    9. Record Locking
    10. Posix Semaphores
    11. System V Semaphores

    如果使用dispatch_async 调用线程不会阻塞。

    When you add a block object or function to a queue, there is no way to know when that code will execute. As a result, adding blocks or functions asynchronously lets you schedule the execution of the code and continue to do other work from the calling thread. This is especially important if you are scheduling the task from your application’s main thread—perhaps in response to some user event.

    2.NSOperationQueue

    NSOperationQueue  setMaxConcurrentOperationCount: 方法可以配置 operation queue 的最 大并发操作数量。设为 1 就表示 queue 每次只能执行一个操作。

    NSOperationQueue 与dispatch_sync 的区别是NSOperationQueue会创建一个线程。并在这个线程里执行。

    也就是说:多线程调用 addOperation: 方法添加一个 operation queue,所有的线程都会立即返回,NSOperationQueue的线程执行完后,会在NSOperationQueue的线程调用block。

    虽然 NSOperationQueue 类设计用于并发执行 Operations,你也可以 强制单个 queue 一次只能执行一个 OperationsetMaxConcurrentOperationCount: 方法可以配置 operation queue 的最 大并发操作数量。设为 1 就表示 queue 每次只能执行一个操作。不过 operation 执行的顺序仍然依赖于其它因素,像操作是否准备好和优先级 等。因此串行化的 operation queue 并不等同于 GCD 中的串行 dispatch queue

     原文:http://www.cnblogs.com/javastart/p/4248290.html

     
  • 相关阅读:
    何时使用Entity或DTO
    Lombok简介
    Spring Boot实现STOMP协议的WebSocket
    Java泛型构造函数
    Java 8 Comparator: 列表排序
    Spring Boot + Elastic stack 记录日志
    Sping、SpringMVC、SpringBoot的对比
    FileChannel指南
    让Spring Boot启动更快
    架构级开闭原则
  • 原文地址:https://www.cnblogs.com/javastart/p/4248290.html
Copyright © 2011-2022 走看看