0

I have this method

- (void) checkIfShouldSendReadingsToServerAsync
    {
    // Check if I want to send the data
    // All other threads should wait hear until I signal them to continue
    if (!self.lastSendRequestToServerDateTime ||
        ([[NSDate date] timeIntervalSinceDate:self.lastSendRequestToServerDateTime]/60.0) > intervalBetweenRequestsToServerInMinutes.doubleValue)
        {
        // Read data from the SQLite database asynchronous and a completion block
        // This call uses a NSOperationQueue block
        [self.sqliteStore readingsToSendToServer:^(NSArray *readingsArray)
            {
            // Loaded the values, now check if I should send them
            if (readingsArray &&
                readingsArray.count > 0)
                {
                // Convert array of objects to JSON
                NSString* json = [self.sqliteStore readingsArrayToJSON:readingsArray];
                // Send the JSON to the server using NSURLSession
                [[WEEServiceRepository sharedInstance] sendJSONReadings:json withCompletionHandler:^(NSError *error, NSURLResponse *response)
                    {
                    // REST POST call ended, check the status code
                    NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
                    NSInteger statusCode = httpResponse.statusCode;
                    self.lastSendRequestToServerDateTime = [NSDate date];
                    switch (statusCode)
                        {
                        case 200:
                        case 201:
                        case 204:
                            {
                            // This call uses a NSOperationQueue block
                            [self.sqliteStore updateReadingsWithSentToServerYes:readingsArray andCompletionBlock:^(BOOL succeed)
                                {
                                // Here allow all other threads or the same thread to enter
                                }];
                                break;
                            }
                        default:
                            {
                            // Or here signal to continue
                            }
                        }
                    }];
                }
            }];
        }
    }

I want this whole method to be thread safe, until the service call returns and signals that it is OK for other threads to continue it should keep them in line.

This code will run when the application is in the foreground but in the background as well. I tried semaphores but for a reason after a while I found that it stopped in the background, deadlock maybe? But it shouldn't! I don't really want to use @synchronized, or am I wrong and go ahead and try? Maybe just use NSLock or NSRecursiveLock?

I try to find the most appropriate way to lock and unlock the section of code, especially when using asynchronous methods.

6
  • NSLock is a better option to use Dec 21, 2014 at 5:40
  • It looks like so, what do you think if I wrap this method too in a NSOperationQueue block and use pthread mutex instead of the NSLock wrapper? Would I gain optimization and speed? Mutex seems to be 50% faster than NSLock.
    – xplat
    Dec 21, 2014 at 5:51
  • Also, it seems that NSLock needs to get unlocked from the same thread that is locked, that is impossible in my case.
    – xplat
    Dec 21, 2014 at 6:00
  • 1
    It's not entirely clear here what you're synchronizing. Perhaps you can update your code sample in your question and show where you are imagining the resource being locked and unlocked. (Your comment about locking and unlocking from different threads esp confused me.) In terms of @synchronized vs NSLock, this doesn't strike me as a situation where there's enough contention for it to matter, but in those cases spin locks, GCD serial queues, and reader-writer patterns are usually more efficient.
    – Rob
    Dec 21, 2014 at 6:53
  • OK, let me make it more clear, I want to lock on the readingsToSendToServer:^(NSArray *readingsArray), no one should read for these resources until I finish the REST call and/or update them.
    – xplat
    Dec 21, 2014 at 16:49

1 Answer 1

0

I ensured thread safety when you have to deal with a series of dependent asynchronous operation with the help of this example, overriding from NSOperation and implementing the properties isExecuting, isFinished and the start method can give you control when the queue will release the operation and proceed to the next one with in my case setting the NSOperationQueue.maxConcurrentOperationCount to 1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.