iOS Thread safety - Complete a block of code before thread switches

人走茶凉 提交于 2019-12-11 04:45:35

问题


I'm looking for a way to make sure that some lines of code get always executed together (before the system may switch the thread).

@synchronized does not work for this as far as I know since it will only block another thread to come into this certain block. In my example I have different code parts that take influence on each other and I want to make sure that each of them blocks the other.

How can this be achieved?

EDIT: One Use Case could be that I'm playing back a midi file. The events go out on a high priority thread automatically. While procoessing the single events the player could be stopped by the user. I want to make sure that either one note gets processed completely or that the player is stopped before and the notes doesn't go off.


回答1:


There is no way to ensure that your code is not preempted by the operating system. You have two options at you disposal to limit the possibility that this happens:

  1. Run you code on a high priority thread. dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH); will return such a queue. Code on this queue will run before code on any other lower priority queue. You still might get preempted though it is less likely.

  2. Use locks, semaphores, @synchrosized or, as suggested by @Rob, a dedicated serial dispatch queue to serialize access to the critical code section. By doing so, no other thread will be able to run that piece of code until the other thread is done. If used correctly, this will guarantee that the code section is not executed by two threads concurrently.

Maybe you can tell us a bit more about your problem? With some code sample perhaps?



来源:https://stackoverflow.com/questions/16131591/ios-thread-safety-complete-a-block-of-code-before-thread-switches

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!