dispatch_semaphore_t
API说明
1、dispatch_semaphore_create ,初始化锁
2、dispatch_semaphore_wait ,阻断,等待信号
3、dispatch_semaphore_signal ,发出信号
下面是自己的理解和例子代码
#import <Foundation/Foundation.h>
@interface NSLockTest : NSObject
- (void)forTest;
@end
#import "NSLockTest.h"
#import <pthread.h>
@interface NSLockTest()
@property (nonatomic,strong) dispatch_semaphore_t semaphore;
@end
@implementation NSLockTest
- (void)forTest
{
// 创建信号量
self.semaphore = dispatch_semaphore_create(2);
NSThread *thread1 = [[NSThread alloc]initWithTarget:self selector:@selector(download1) object:nil];
[thread1 start];
NSThread *thread2 = [[NSThread alloc]initWithTarget:self selector:@selector(download2) object:nil];
[thread2 start];
NSThread *thread3 = [[NSThread alloc]initWithTarget:self selector:@selector(download3) object:nil];
[thread3 start];
NSThread *thread4 = [[NSThread alloc]initWithTarget:self selector:@selector(download4) object:nil];
[thread4 start];
}
-(void)download1
{
dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"download1 begin");
sleep(arc4random()%2);
NSLog(@"download1 end");
dispatch_semaphore_signal(self.semaphore);
[self download1];
}
-(void)download2
{
dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"download2 begin");
sleep(arc4random()%2);
NSLog(@"download2 end");
dispatch_semaphore_signal(self.semaphore);
[self download2];
}
-(void)download3
{
dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"download3 begin");
sleep(arc4random()%2);
NSLog(@"download3 end");
dispatch_semaphore_signal(self.semaphore);
[self download3];
}
-(void)download4
{
dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"download4 begin");
sleep(arc4random()%2);
NSLog(@"download4 end");
dispatch_semaphore_signal(self.semaphore);
[self download4];
}
@end
注意
dispatch_semaphore_t,使用过信号量来控制线程之间的同步
1、dispatch_semaphore_create(long value); 创建一个信号量,value是初始值,大体意思是同时允许多少线程运行,demo中初始值是2
2、dispatch_semaphore_wait(dispatch_semaphore_t dsema, dispatch_time_t timeout); 这时候信号量会-1,变为1
3、如果有其他线程继续运行,那么继续-1,变为0
4、此时如果还有其他线程想运行,因为此时的value变为了0,该线程就阻塞了,必须等其他进程发出信号量
5、线程运行完调用,dispatch_semaphore_signal(dispatch_semaphore_t dsema); 这时候信号量会+1,变为1.
6、这时候4
中的线程得到信号通知,继续执行操作,即信号量-1,变为0.
网友评论