简体   繁体   中英

How to add background task in same global queue?

I'm coding something like a work thread or background thread thing on iOS. Every time a task came in, I put it into a background thread. But the problem is, I don't want to use this dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{}); every time, because it will make the task run in different thread, and create a thread costs a lot time.

So my question is how to make a GCD queue and put it run in same background thread, I will make it run back to main thread when it result came out.

You seem to be using "thread" and "queue" like they are the same thing. They are not. A queue is a higher level abstraction that may be implemented using 1 or more actual threads.

Using dispatch_get_global_queue is likely to give you a different queue each time. So the first thing you need to do is to create a single queue that you use instead of asking for a new queue each time. Use dispatch_queue_create to create a single queue. Store a reference to that at some appropriate scope so you can reference it where ever you need it.

Now that you have just a single queue, you need to decided if the queue should be a concurrent queue or a serial queue. A serial queue will only use 1 thread while a concurrent queue can use multiple threads. You get the desired queue by passing the proper value to the attr parameter of the dispatch_queue_create function.

Objective-C:

Create the queue:

dispatch_queue_t myQueue = dispatch_queue_create(@"my_global_queue", DISPATCH_QUEUE_CONCURRENT); // or use DISPATCH_QUEUE_SERIAL

Use the queue:

dispatch_async(myQueue, ^{
    // code
});

Swift:

Create the queue:

let myQueue = DispatchQueue(label: "my_global_queue") // serial

or:

let myQueue = DispatchQueue(label: "my_global_queue", attributes: .concurrent) // concurrent

Use the queue:

myQueue.async {
    // code
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM