0

I understand that

 @synchronized(self) { /* lock is effective inside here only */ } 

can keep multiple threads from accessing your method at the same time. So no one will be able to access what's inside the @synchronized{} while it is being used.

I there someway that I will allow only a limited number of threads, for example allow only 2 threads or 3 threads to access the method at the same time.

PS: I have a method which send synchronous Request, and I want to limit sending synchronous request at maximum of 3 at a time

   @synchronized(self) { 
  webData  = [NSURLConnection sendSynchronousRequest: request returningResponse: &response  error: &error]; 
   }
Glenn S
  • 697
  • 9
  • 21

2 Answers2

2

Using an NSOperationQueue (as Bob Kinney suggests) is a good idea. If for some reason you don't like it, you can use a GCD semaphore.

E.g.

@implementation MyObject {
    dispatch_semaphore_t semaphore_;
}

- (id)init {
    if ((self = [super init])) {
        semaphore_ = dispatch_semaphore_create(3);
    }
}

- (void)dealloc {
    dispatch_release(semaphore_);
}

- (void)doTheThing {
    dispatch_semaphore_wait(semaphore_, DISPATCH_TIME_FOREVER); {
        // Do expensive operation here.  At most 3 threads can do it at once.
    } dispatch_semaphore_signal(semaphore_);
}

Read about “Using Dispatch Semaphores to Regulate the Use of Finite Resources” in the Concurrency Programming Guide for more.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
1

Perhaps it would be better if you tried to explain your use case. If your goal is to limit a number of running processes, I would encourage you to examine NSOperation and NSOperationQueue as this will give you that functionality.

Concurrency Programming Guide

NSOperationQueue

Bob Kinney
  • 8,870
  • 1
  • 27
  • 35