Max
Max

Reputation: 2749

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

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.

Upvotes: 1

Views: 588

Answers (1)

aLevelOfIndirection
aLevelOfIndirection

Reputation: 3522

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?

Upvotes: 1

Related Questions