dispatch_async中的同步块 [英] synchronized block within dispatch_async

查看:78
本文介绍了dispatch_async中的同步块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了将异步分派到主队列或私有分派队列(串行)的代码,然后在分派代码块中进行了@synchronized.您想在什么情况下这样做?串行队列是否已不提供所需的同步?

I have seen code that dispatch async to a main queue or private dispatch queue (serial) and then in the dispatch code block is @synchronized. Under what circumstance do you want to do that? Isn't a serial queue already providing the synchronization needed?

可以将同步块替换为另一个GCD调度吗?

Can the synchronized block be replaced with another GCD dispatch?

推荐答案

@synchronized()确保所包含的代码(对于给定标记作为@synchronized的参数)一次仅在一个线程上运行.

@synchronized() ensures that contained code (for a given token as the argument to @synchronized) is only run on one thread at a time.

提交给串行队列的块一次执行一次,即.给定的块直到执行完毕之前提交的所有块都不会执行.只要仅从串行队列上运行的代码访问共享资源,就无需同步/锁定对其的访问.但是,仅由于给定的队列是串行队列,并不意味着其他队列/线程(甚至串行队列!)不是同时运行,也不是在访问相同的共享资源.

Blocks submitted to a serial queue are executed one at a time, ie. a given block is not executed until all blocks submitted before it have finished executing. As long as a shared resource is only being accessed from code running on a serial queue, there's no need to synchronize/lock access to it. However, just because a given queue is serial, doesn't mean that other queues/threads (even serial queues!) aren't running simultaneously, and accessing the same shared resource.

使用@synchronized()是防止这些多个线程/队列同时访问资源的一种方法.请注意,访问共享资源的所有代码需要用@synchronized()包装.

Using @synchronized() is one way to prevent these multiple threads/queues from accessing the resource at the same time. Note that all code that access the shared resource needs to be wrapped with @synchronized().

是的,您可以使用其他GCD调度而不是同步块.这样做的"GCD方式"将是使用串行队列将对共享资源的所有访问序列化.因此,只要需要访问共享资源,就可以将代码(根据使用情况,使用dispatch_sync()dispatch_async())分派给与该资源关联的串行队列.当然,这意味着资源访问队列必须对访问共享资源的程序的所有部分都是可见/可访问的. (与@synchronized()基本上存在相同的问题,因为它的锁定令牌必须在需要使用的任何地方都可以访问,但是因为它可以是字符串常量,所以它要容易一些.)

Yes, you can use another GCD dispatch instead of a synchronized block. The "GCD way" of doing this would be to serialize all access to the shared resource using a serial queue. So, any time access to the shared resource needs to be made, you dispatch that code (using either dispatch_sync() or dispatch_async() depending on use case) to the serial queue associated with the resource. Of course, this means that the resource-access-queue must be visible/accessible to all parts of the program that access the shared resource. (You essentially have the same problem with @synchronized() in that its lock token must be accessible wherever it needs to be used, but it's a little easier since it can just be a string constant.)

这篇关于dispatch_async中的同步块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆