2016-06-29 4 views
6

저는 Apple의 GCD에 대해 배우고 비디오를 보니 Concurrent Programming With GCD in Swift 3입니다.`sync`로 큐에 디스패치하는 것과`.wait` 플래그로 작업 항목을 사용하는 것의 차이점은 무엇입니까?

이 비디오의 16:00에서 DispatchWorkItem에 대한 플래그는 .wait이라고하며, 기능과 다이어그램 모두 myQueue.sync(execute:)이 정확히 무엇을 나타내는지를 보여줍니다.

.wait diagram

그래서, 내 질문은,

myQueue.sync { sleep(1); print("sync") } 

과 : 차이점은 무엇입니까

myQueue.async(flags: .wait) { sleep(1); print("wait") } 
// NOTE: This syntax doesn't compile, I'm not sure where the `.wait` flag moved to. 
// `.wait` Seems not to be in the DispatchWorkItemFlags enum. 

보인다 그들이에 명명 된 큐를 기다리는 동안 두 가지 접근 방식은 현재 스레드를 차단 같은 :

  1. 마침 현재 또는 이전을 일 (연속 일 경우)
  2. 주어진 블록/작업 항목 완료

내 이해가 어딘가에 있어야하며, 무엇이 누락 되었습니까?

답변

8

.waitDispatchWorkItemFlags에서 하지 플래그이며, 코드가

myQueue.async(flags: .wait) { sleep(1); print("wait") } 

컴파일되지 않는 이유입니다.

wait() is a method of DispatchWorkItem 그리고 단지 dispatch_block_wait()에 대한 래퍼입니다.

/*! 
* @function dispatch_block_wait 
* 
* @abstract 
* Wait synchronously until execution of the specified dispatch block object has 
* completed or until the specified timeout has elapsed. 

간단한 예 :

let myQueue = DispatchQueue(label: "my.queue", attributes: .concurrent) 
let workItem = DispatchWorkItem { 
    sleep(1) 
    print("done") 
} 
myQueue.async(execute: workItem) 
print("before waiting") 
workItem.wait() 
print("after waiting") 

dispatchMain() 
+0

감사합니다. 'sync'보다 좀 더 세분화 된 컨트롤을 제공하는 것처럼 보입니다. 'dispatchMain()'은 무엇을하고 있습니까? – SimplGy

+0

@ SimplGy : https://developer.apple.com/reference/dispatch/1452860-dispatch_main. GCD를 계속 실행하려면 runloop이없는 프로그램 (명령 줄 프로그램 등)이 필요합니다. 놀이터에서'PlaygroundPage.current.needsIndefiniteExecution = true' (와)과 동일한 효과를 얻습니다 (http://stackoverflow.com/questions/24058336/how-do-i-run-asynchronous-callbacks-in-playground).) –

+0

@MartinR 고마워요! 작은 질문 : 'workItem' 블록 안의 코드가 비동기이면 어떻게 될까요? 예를 들어'SKTextureAtlas'의'preload (completionHandler :)'와 같은 것입니다. 'workItem'이 코드가 끝날 때까지 기다렸다가 완료되었다고 표시하는 것을 어떻게 보장 할 수 있습니까? – damirstuhec