从并发线程同时在主 DispatchQueue 上调度块是否安全?

Is it safe to schedule blocks on the main DispatchQueue at the same time from concurrent threads?

在我的代码中,我使用 for 循环将并发任务分派到全局分派队列,如下所示:

for collectionMember in myCollection {
    DispatchQueue.global(qos: .default).async {

        // do stuff here with collectionMember and store in variable "result"

        DispatchQueue.main.async {
            // code using variable "result" that must be executed serially on main thread
            // because accesses shared resources
        }
}

我是整个 Grand Central Dispatch 的新手,我担心当不同的并发线程尝试在主 DispatchQueue 上调度块时,会出现一些内存问题,因为它们都访问主 DispatchQueue。

我希望并发线程在完成时向主 DispatchQueue 添加一个块,而不会出现线程安全问题。

我是否必须在将代码分派到主 DispatchQueue 的块周围使用锁,或者调度块线程是否安全?

最后,如果我有任何错误或者有更简单的方法来解决这个问题,请告诉我。 谢谢!

不需要锁。主队列锁了!这就是重点(嗯,很多重点)。它是一个串行队列;只要其他东西已经在执行,就不能在主队列上开始执行。主线程内没有并发。你所做的是完全正确的;请注意,您可能正在排列一大堆要在主线程上执行的块,一次一个。但这不是问题,除非这里有很多。