iOS 线程安全 - 在线程切换前完成一段代码 [英] iOS Thread safety - Complete a block of code before thread switches

查看:39
本文介绍了iOS 线程安全 - 在线程切换前完成一段代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来确保某些代码行始终一起执行(在系统可能切换线程之前).

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 据我所知对此不起作用,因为它只会阻止另一个线程进入该特定块.在我的示例中,我有不同的代码部分相互影响,我想确保它们中的每一个都阻止另一个.

@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.

如何实现?

一个用例可能是我正在播放一个 MIDI 文件.事件在高优先级线程上自动退出.在处理单个事件时,用户可以停止播放器.我想确保一个音符得到完全处理,或者播放器之前停止并且音符不会消失.

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.

推荐答案

没有办法确保您的代码不被操作系统抢占.您有两种选择可以限制发生这种情况的可能性:

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. 在高优先级线程上运行代码.dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH); 将返回这样一个队列.此队列上的代码将在任何其他较低优先级队列上的代码之前运行.您仍然可能会被抢占,尽管可能性较小.

  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.

使用锁、信号量、@synchrosized 或@Rob 建议的专用串行调度队列来序列化对关键代码部分的访问.通过这样做,在另一个线程完成之前,没有其他线程能够运行那段代码.如果使用得当,这将保证代码部分不会被两个线程同时执行.

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?

这篇关于iOS 线程安全 - 在线程切换前完成一段代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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