gpt4 book ai didi

swift - 在OperationQueue中打印1到10不打印整数

转载 作者:行者123 更新时间:2023-12-03 13:02:04 27 4
gpt4 key购买 nike

我正在研究Combine Scheduler,我从Raywenderlich的书中获得了此示例代码

let queue = OperationQueue()

let subscription = (1...10).publisher
.receive(on: queue)
.sink { value in
print("Received \(value) on thread \(Thread.current.number)")
}

这本书解释了OperationQueue使用所有可用线程,因此打印顺序和线程可能是随机的。我理解这部分,但是当我在操场上运行此代码时,我只看到10个数字中的5个。
Received 1 on thread 7
Received 2 on thread 6
Received 3 on thread 5
Received 7 on thread 9
Received 6 on thread 4
为什么该代码不能显示全部10个数字?

最佳答案

您需要导入PlaygroundSupport并在文件顶部设置PlaygroundPage.current.needsIndefiniteExecution = true
如果您使用其他接收器方法,也将获得一个完成处理程序块的接收器方法,则在该完成处理程序中,应调用PlaygroundPage.current.finishExecution()编辑:在队列的屏障块中调用PlaygroundPage.current.finishExecution(),否则在您的打印语句全部执行之前被调用。
这是我的测试代码:

PlaygroundPage.current.needsIndefiniteExecution = true

let queue = OperationQueue()

let subscription = (1...10).publisher
.receive(on: queue)
.sink(receiveCompletion: { _ in
queue.addBarrierBlock {
print("Finished")
PlaygroundPage.current.finishExecution()
}
}, receiveValue: { value in
print("Received \(value) on thread \(Thread.current)")
})
并输出:
Received 1 on thread <NSThread: 0x7fd86f204080>{number = 2, name = (null)}
Received 2 on thread <NSThread: 0x7fd86f404340>{number = 3, name = (null)}
Received 3 on thread <NSThread: 0x7fd86f404430>{number = 4, name = (null)}
Received 7 on thread <NSThread: 0x7fd86f405240>{number = 5, name = (null)}
Received 6 on thread <NSThread: 0x7fd86f205c50>{number = 6, name = (null)}
Received 10 on thread <NSThread: 0x7fd86ce487f0>{number = 7, name = (null)}
Received 5 on thread <NSThread: 0x7fd86cf048a0>{number = 10, name = (null)}
Received 9 on thread <NSThread: 0x7fd86ce49b20>{number = 11, name = (null)}
Received 4 on thread <NSThread: 0x7fd86cf2a4c0>{number = 12, name = (null)}
Received 8 on thread <NSThread: 0x7fd86ce4ad60>{number = 13, name = (null)}
Finished

关于swift - 在OperationQueue中打印1到10不打印整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64674464/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com