Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a custom sequential global dispatch queue

In many places in my app I use the next code to perform background tasks and notify the main thread:

dispatch_queue_t backgroundQueue = dispatch_queue_create("dispatch_queue_#1", 0);
    dispatch_async(backgroundQueue, ^{

   dispatch_async(dispatch_get_main_queue(), ^{


        });
    });

Is it possible to create a backgroundQueue in one place (where does the best way?) and use it later? I know about the system global queue, but ordering is important for me.

like image 263
pvllnspk Avatar asked Aug 01 '13 17:08

pvllnspk


People also ask

How do I create a serial dispatch queue?

serial when creating a serial queue: let serialQueue = DispatchQueue(label: "queuename") . In Xcode 8 beta 4 there is no . serial option so you have to create serial queue by omitting the . concurrent in attributes.

What is global dispatch queue?

A dispatch queue that executes tasks serially in first-in, first-out (FIFO) order. typealias dispatch_queue_concurrent_t. A dispatch queue that executes tasks concurrently and in any order, respecting any barriers that may be in place.

Is DispatchQueue global serial?

The main dispatch queue is a globally available serial queue executing tasks on the application's main thread.

What is global queue in Swift?

The global queues are concurrent queues and from the main page for dispatch_get_global_queue: Unlike the main queue or queues allocated with dispatch_queue_create(), the global concurrent queues schedule blocks as soon as threads become available ("non-FIFO" completion order).


2 Answers

Something like this should work fine:

dispatch_queue_t backgroundQueue() {
    static dispatch_once_t queueCreationGuard;
    static dispatch_queue_t queue;
    dispatch_once(&queueCreationGuard, ^{
        queue = dispatch_queue_create("com.something.myapp.backgroundQueue", 0);
    });
    return queue;
}
like image 146
Catfish_Man Avatar answered Oct 21 '22 16:10

Catfish_Man


queue = dispatch_queue_create("com.something.myapp.backgroundQueue", 0);

Preceding is Serial Queue,if you want create concurrent queue,you can use DISPATCH_QUEUE_CONCURRENT.

In iOS 5 and later, you can create concurrent dispatch queues yourself by specifying DISPATCH_QUEUE_CONCURRENT as the queue type.

dispatch_queue_t queue = dispatch_queue_create("downLoadAGroupPhoto",
                                                   DISPATCH_QUEUE_CONCURRENT);
like image 1
AllanXing Avatar answered Oct 21 '22 16:10

AllanXing