0

I have two queues which both of them are serial with different identifier. In my code, I will dispatch a queue1 first and then inside the queue I will dispatch another queue.

Sample Code:

var queue1 = dispatch_queue_create ("com.sample.Queue1", DISPATCH_QUEUE_SERIAL)
var queue2 = dispatch_queue_create ("com.sample.Queue2", DISPATCH_QUEUE_SERIAL)

func function1(){
    dispatch_sync(self.queue1, { //queue1
        //LineA
        dispatch_sync(self.queue2,{ //queue2
            //LineB
            //Some function need network communication
        })
    })
}

I will keep execute function1, so all the code inside function1 will queue up and run once at a time. (No concurrency)

But, if I run another queue inside queue1, LineA will call before queue2 finish all the code.

Question:

  1. I would like to know how to lock queue1 before queue2 finish the code. I would like to wait until queue2 finish the code before run a new queue1.
  2. Are there any concepts I have misunderstood?

Sorry for my english and I am new to multi-thread programming.

HARZI
  • 171
  • 1
  • 8
  • I know this method, but my problem is the second queue2 is some third party code, I dont want to modify the queue2 code. – HARZI Feb 10 '16 at 11:10
  • oh i found the second reply useful in that post. thank you – HARZI Feb 10 '16 at 11:22
  • Check [this](http://stackoverflow.com/questions/11909629/waiting-until-two-async-blocks-are-executed-before-starting-another-block) post. This should work for you! – TechBee Feb 10 '16 at 11:32
  • I'm confused. `dispatch_sync` is a *blocking* operation, so queue1 will already wait for queue2 to finish processing before continuing. If you're scheduling an **asynchronous** operation within that queue, then you should be using a `dispatch_group` or a semaphore in order to synchronise your tasks. See [this answer](http://stackoverflow.com/a/20910658/2976878) on the above linked post for details on how to use a `dispatch_group` for an asynchronous task. – Hamish Feb 10 '16 at 12:08
  • Also, if you **don't** want concurrency, why are you using two serial queues? Just use a single queue to synchronise operations. Also you should be using `dispatch_async` to avoid blocking the main thread. – Hamish Feb 10 '16 at 12:12
  • thanks @originaluser2 I think i have misunderstood the meaning of `dispatch_sync` and `dispatch_async`. I am reading the post and testing the playground. – HARZI Feb 10 '16 at 12:52

0 Answers0