iOS并发编程指南之同步
1.gcd
fmdb使用了gcd,它是通過 建立系列化的G-C-D隊列 從多線程同時調用調用方法,GCD也會按它接收的塊的順序來執行。
fmdb使用的是dispatch_sync,多線程調用a serialized queue,gcd會在接收塊的線程執行,并阻塞其他線程。
?
?
使用FMDatabaseQueue 及線程安全?
在多個 線程中同時使用一個FMDatabase實例是不明智的?,F在你可以為每個線程創建一個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 一次只能執行一個 Operation。 setMaxConcurrentOperationCount: 方法可以配置 operation queue 的最 大并發操作數量。設為 1 就表示 queue 每次只能執行一個操作。不過 operation 執行的順序仍然依賴于其它因素,像操作是否準備好和優先級 等。因此串行化的 operation queue 并不等同于 GCD 中的串行 dispatch queue。
?
?
?原文:http://www.cnblogs.com/javastart/p/4248290.html
?
轉載于:https://www.cnblogs.com/javastart/p/4248290.html
總結
以上是生活随笔為你收集整理的iOS并发编程指南之同步的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 苹果系统改win7密码怎么设置密码 wi
- 下一篇: hdu 2025 查找最大元素 (水)