1、DISPATCH_QUEUE_SERIAL
1.1、串行队列使队列中的任务同步执行,单次只能执行一个任务
1.2、示例代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| #import "ViewController.h"
#import <pthread.h>
@implementation ViewController
static NSUInteger ticketCount_ = 20;
- (void)viewDidLoad
{
[super viewDidLoad];
dispatch_queue_t queue = dispatch_queue_create("com.yusian.custom-queue", DISPATCH_QUEUE_SERIAL);
for (int i = 0; i < 5; i++) {
dispatch_async(queue, ^{
[self saleTicket];
});
}
}
- (void)saleTicket
{
NSUInteger remain = ticketCount_;
sleep(1);
ticketCount_ = --remain;
NSLog(@"%ld, %@", ticketCount_, [NSThread currentThread]);
}
@end |
#import "ViewController.h"
#import <pthread.h>
@implementation ViewController
static NSUInteger ticketCount_ = 20;
- (void)viewDidLoad
{
[super viewDidLoad];
dispatch_queue_t queue = dispatch_queue_create("com.yusian.custom-queue", DISPATCH_QUEUE_SERIAL);
for (int i = 0; i < 5; i++) {
dispatch_async(queue, ^{
[self saleTicket];
});
}
}
- (void)saleTicket
{
NSUInteger remain = ticketCount_;
sleep(1);
ticketCount_ = --remain;
NSLog(@"%ld, %@", ticketCount_, [NSThread currentThread]);
}
@end
执行结果:[……]
继续阅读