Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/121.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
ios允许同时使用某个方法在上运行特定数量的线程_Ios_Multithreading_Synchronized_Locks - Fatal编程技术网

ios允许同时使用某个方法在上运行特定数量的线程

ios允许同时使用某个方法在上运行特定数量的线程,ios,multithreading,synchronized,locks,Ios,Multithreading,Synchronized,Locks,我明白 @synchronized(self) { /* lock is effective inside here only */ } 可以防止多个线程同时访问您的方法。因此,在使用@synchronized{}时,没有人能够访问它内部的内容 在某种程度上,我只允许有限数量的线程,例如,只允许2个线程或3个线程同时访问该方法 PS:我有一个发送同步请求的方法,我想限制每次最多发送3个同步请求 @synchronized(self) { webData = [NSURLCon

我明白

 @synchronized(self) { /* lock is effective inside here only */ } 
可以防止多个线程同时访问您的方法。因此,在使用@synchronized{}时,没有人能够访问它内部的内容

在某种程度上,我只允许有限数量的线程,例如,只允许2个线程或3个线程同时访问该方法

PS:我有一个发送同步请求的方法,我想限制每次最多发送3个同步请求

   @synchronized(self) { 
  webData  = [NSURLConnection sendSynchronousRequest: request returningResponse: &response  error: &error]; 
   }

如果您尝试解释您的用例,也许会更好。如果您的目标是限制运行进程的数量,我建议您检查
NSOperation
NSOperationQueue
,因为这将为您提供该功能


如果您尝试解释您的用例,可能会更好。如果您的目标是限制运行进程的数量,我建议您检查
NSOperation
NSOperationQueue
,因为这将为您提供该功能


使用
NSOperationQueue
(正如Bob Kinney所建议的)是一个好主意。如果出于某种原因您不喜欢它,您可以使用GCD信号量

例如


更多信息。

使用
NSOperationQueue
(正如Bob Kinney所建议的)是个好主意。如果出于某种原因您不喜欢它,您可以使用GCD信号量

例如

更多

@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_);
}