文件1:ViewController.m
#import "ViewController.h"int mumber = 0;
@interface ViewController ()
{
dispatch_queue_t queue;
NSLock *lock;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
queue = dispatch_queue_create("xxx", DISPATCH_QUEUE_SERIAL);
lock = [[NSLock alloc] init];
//Main queue,提交到Main queue的队列会在主线程中执行,是串行队列
dispatch_queue_t mainQueue = dispatch_get_main_queue();
dispatch_async(mainQueue, ^{
for (int i = 0; i<100; i++) {
NSLog(@"%@:%i",[NSThread isMainThread]?@"Main thread":@"Sub thread",i);
}
NSLog(@"+++");
});
//死锁 这是循环等待造成的
// NSLog(@"---------");
// dispatch_sync(mainQueue, ^{
// NSLog(@"dispatch_sync");
// });
dispatch_queue_t queue1 = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue1, ^{
NSLog(@"%@",[NSThread isMainThread]?@"Main":@"Sub");
});
dispatch_sync(queue1, ^{
NSLog(@"%@",[NSThread isMainThread]?@"Main":@"Sub");
dispatch_async(dispatch_get_main_queue(), ^{
self.view.backgroundColor = [UIColor blackColor];
});
});
dispatch_queue_t queue2 = dispatch_queue_create("yyy", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue2, ^{
for (int i = 0; i<100; i++) {
[self setFlag:1];
}
});
dispatch_async(queue2, ^{
for (int i = 0; i<100; i++) {
[self setFlag:2];
}
});
//提交重复任务
dispatch_async(queue2, ^{
for (int i = 0; i<100; i++) {
[self setFlag:3];
}
});
dispatch_apply(3, queue2, ^(size_t iteraction){
NSLog(@"%zu",iteraction);
});
// Do any additional setup after loading the view, typically from a nib.
}
- (void)setFlag:(int)value
{
//加锁
// @synchronized(self) {
// //临界区
// num ++;
// NSLog(@"serial %d: %d", value, num);
// }
//线程间同步
// dispatch_async(queue3, ^{
// num ++;
// NSLog(@"serial %d: %d", value, num);
// });
//
[lock lock];
mumber ++;
NSLog(@"serial %d: %d", value, mumber);
[lock unlock];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
文件2:MySingleton.h
#import <Foundation/Foundation.h>
@interface MySingleton : NSObject
+ (instancetype)instance;
@end
文件3:MySingleton.m
#import "MySingleton.h"@implementation MySingleton
+ (instancetype)instance
{
static MySingleton *instance = nil;
static dispatch_once_t onceToke ;
dispatch_once(&onceToke,^{
instance = [[MySingleton alloc] init];
});
return instance;
}
@end