日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

iOS并发编程指南之同步

發布時間:2024/10/12 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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并发编程指南之同步的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。