0
Utility.managedObjectContext().performBlockAndWait({

})

dispatch_sync(dispatch_get_main_queue(), {

})
  1. 好奇上面的两个代码有什么区别?上下文是使用.MainQueueConcurrencyType选项创建的。
  2. 如果我在主队列上执行块,队列是否按 FIFO 顺序执行?或者它们可以重叠,操作混合?即 (a1,a2,a3),(b1,b2,b3) 可以导致 (a1,b1,a2,a3,b2,b3)?
4

1 回答 1

1

You are mixing two entirely different concepts here, but since it is the main thread/context/queue, your mix is masked and it "works".

Managed object context's performBlockAndWait: and performBlock: methods do not make any guarantees on which thread the block is executed, only that data accessed/mutated is safely accessed. Since your context is of main queue concurrency type, it is the exception in that it is safe to touch its objects outside of the performBlockAndWait: and performBlock: methods, on the main thread only. So when you queue your block to run on the main queue, it is guaranteed to run on the main thread, and thus your data is safe.

Block execution on the main thread is not atomic. Otherwise, what is the point of multithreading? To ensure data safety, you must performBlockAndWait: and performBlock: methods are called when accessing data. You are guaranteed that main queue scheduled blocks will run uninterrupted by other main queue scheduled blocks, and managed object context queues (background or main) are serial, so only one block will be allowed to concurrently access data.

于 2015-05-12T09:28:59.837 回答