ios – Apple doc的GCD Producer – 消費者解決方案出錯?
在Apple的併發程式設計指南中的“遷移執行緒”部分中,有
ofollow,noindex" target="_blank">Changing Producer-Consumer Implementations,其聲稱可以使用GCD簡化典型的多步pthread互斥條件變數實現.
With dispatch queues, you can simplify the producer and consumerimplementations into a single call:
dispatch_async(queue, ^{ // Process a work item. });
When your producer has work to be done, all it has to do is add that work to a queue and let the queue process the item.
生產者 – 消費者問題也被稱為邊界緩衝區問題,但上面沒有提到緩衝區,其繫結或消費者,更不用說阻止生產者和消費者.消費者為了避免上下執行.
這怎麼可以成為一個有效的解決方案?
在蘋果檔案中所述的解決方案中:
>沒有緩衝區,因為不需要緩衝區;
系統負載是有限的;
>消費者是任務.
假設您有多個生產者和消費者,生產者將資料放在共享緩衝區中,消費者從該共享緩衝區讀取資料.訊號量或監視器用於同步對共享緩衝區的訪問,並且緩衝區大小是固定的,以便根據消耗的速率來限制正在生成的資料量,從而限制生產者.
在大中央排程下,消費者是派遣到佇列的任務.由於任務是Objective-C塊,生產者不需要緩衝區來告訴消費者它應該處理的資料:Objective-C塊自動捕獲它們引用的物件.
例如:
// Producer implementation while (…) { id dataProducedByTheProducer; // Produce data and place it in dataProducedByTheProducer dataProducedByTheProducer = …; // Dispatch a new consumer task dispatch_async(queue, ^{ // This task, which is an Objective-C block, is a consumer. // // Do something with dataProducedByTheProducer, which is // the data that would otherwise be placed in the shared // buffer of a traditional, semaphore-based producer-consumer // implementation. // // Note that an Objective-C block automatically keeps a // strong reference to any Objective-C object referenced // inside of it, and the block releases said object when // the block itself is released. NSString *s = [dataProducedByTheProducer …]; }); }
生產者可以將盡可能多的消費者任務作為可以生產的資料.但是,這並不意味著GCD將以相同的速度觸發消費者的任務. GCD使用作業系統資訊來控制根據當前系統負載執行的任務量.生產者本身並沒有節制,在大多數情況下,它不一定是因為GCD的內在負載平衡.
如果實際上需要限制生產者,那麼一個解決方案就是擁有一個能夠分配n個生產者任務的主人,並讓每個消費者通知主人(通過消費者完成工作之後派生的任務)已經結束,其中主人將派遣另一個生產者任務.或者,消費者本身可以在完成時分派生產者任務.
具體回答您解答的內容:
The Producer-Consumer problem is also known as the Bounded-Buffer problem, yet the above makes no mention of a buffer
不需要共享緩衝區,因為消費者是Objective-C塊,它自動捕獲他們引用的資料.
its bound
GCD根據當前系統負載限制已分派任務的數量.
or the consumer
消費者是派往GCD佇列的任務.
let alone blocking the producer & consumer in order to avoid over/under runs
沒有必要阻止,因為沒有共享緩衝區.由於每個消費者都是通過Objective-C塊上下文捕獲機制捕獲生成的資料的Objective-C塊,消費者和資料之間存在一對一的關係.
http://stackoverflow.com/questions/7792074/apple-docs-gcd-producer-consumer-solution-wrong