信号量と同時制御
4440 ワード
コード1-信号量制御を使用しない同時:
出力:
コード-信号量を使用してコンカレントを制御します.
出力:
転載先:https://www.cnblogs.com/xwoder/p/7460783.html
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
for (NSUInteger i = 0; i < 10; ++i) {
NSLog(@"Task - 1");
}
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
for (NSUInteger i = 0; i < 10; ++i) {
NSLog(@"Task - 2");
}
});
}
@end
出力:
Task - 1
Task - 2
Task - 1
Task - 2
Task - 1
Task - 2
Task - 1
Task - 2
Task - 1
Task - 2
Task - 1
Task - 2
Task - 1
Task - 2
Task - 1
Task - 2
Task - 1
Task - 2
Task - 1
Task - 2
コード-信号量を使用してコンカレントを制御します.
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) dispatch_semaphore_t semaphore;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.semaphore = dispatch_semaphore_create(1);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER);
for (NSUInteger i = 0; i < 10; ++i) {
NSLog(@"Task - 1");
}
dispatch_semaphore_signal(self.semaphore);
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER);
for (NSUInteger i = 0; i < 10; ++i) {
NSLog(@"Task - 2");
}
dispatch_semaphore_signal(self.semaphore);
});
}
@end
出力:
Task - 1
Task - 1
Task - 1
Task - 1
Task - 1
Task - 1
Task - 1
Task - 1
Task - 1
Task - 1
Task - 2
Task - 2
Task - 2
Task - 2
Task - 2
Task - 2
Task - 2
Task - 2
Task - 2
Task - 2
転載先:https://www.cnblogs.com/xwoder/p/7460783.html