Smart Home
Smart Home

Reputation: 811

What happens to main queue/main thread, when a dispatch_sync is issued from main thread targeting another dispatch queue?

Suppose I call the method below on the main thread. If some other thread is doing a write on the array at the time the method is called, the dispatch_sync will block. But it is blocking on another queue (not main queue). When this is blocked, what is the state on the main queue (method cannot move forward until the disaptch_sync returns, but is this treated like a asynchronous call on the main queue). For e.g: will the main queue respond to UI events? If yes, what will happen to the state of the method call when dispatch_sync returns when the reaction to user event is happening?

-(id) objectAtIndex:(NSUInteger)index
{
    __block id obj;
    dispatch_sync(self.dataAccessQ, ^{
        obj = self.embeddedArray[index];
    });
    return obj;
}

Upvotes: 1

Views: 167

Answers (2)

rmaddy
rmaddy

Reputation: 318814

It doesn't matter whether it's the main queue or not. Whatever queue is used to call objectAtIndex: will block on the dispatch_sync call until it completes.

If you call this code on the main queue, it blocks like any other queue. During that time, no user events will be processed. The UI will appear locked during that time. When done, the UI will again work as normal.

Upvotes: 1

Amin Negm-Awad
Amin Negm-Awad

Reputation: 16660

No, the main queue is akin of blocked, too.

The main queue is bound to the main thread. Every thread can execute one and only one control flow at a time. If any code is executed on the main thread, no other code can be executed.

Therefore waiting for the result of an operation subscripted to another queue will block the waiting thread. (Not a parallel Q!) This is why we have completion handlers.

Instead of returning an object, add a parameter for a completion handler to your method and call that inside the block at the end.

Upvotes: 1

Related Questions