Naresh
Naresh

Reputation: 344

Code running twice in dispatch_async on the same thread - objective c, ios

I have a method which gets called when receiving data from the network. Just out of curiosity I kept a counter to check if the async calls to the same thread are synchronous. I know its dumb, but I found something strange.

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSLog(@"counterForAsync=%d",counterForAsync);
            ++counterForAsync;
            if (file)  {
                [file seekToEndOfFile];
            }
            [file writeData:data];
});

I copied the console log and observed it in sublime, and saw that some line were repeated.

enter image description here

enter image description here

same thing in on a few other lines. If it is running twice then its bad because I am performing file operation in my async thread.

Upvotes: 0

Views: 870

Answers (1)

sj-r
sj-r

Reputation: 571

There are two types of dispatch queues.

  • serial
  • concurrent

A serial queue(like the main queue) executes the enqueued closures "in order" that you enqueue, one at a time.

However, a concurrent queue(like global dispatch queue) executes the closures concurrently. (Take a look at the Apple documentation)

In those cases where the same counter number is printed twice, 309th closure NSLogged the counter before 308th closure added 1 to the counter. (Do you get it?)

So for the file write operation you should use serial queue like below, as the documentation states

Serial queues are often used to synchronize access to a specific resource.

dispatch_queue_t serialQueue = dispatch_queue_create("com.myqueue.filewrite", DISPATCH_QUEUE_SERIAL);

dispatch_async(serialQueue, ^{
    NSLog(@"counterForAsync=%d",counterForAsync);
        ++counterForAsync;
        if (file)  {
            [file seekToEndOfFile];
        }
        [file writeData:data];
});

FYI, this is called synchronization. You should synchronize your code so that your critical section(like adding a counter or writing to a file) is not accessed by more than two threads at the same time.

Upvotes: 4

Related Questions