Skip to content

Instantly share code, notes, and snippets.

@piaoapiao
Created January 29, 2013 08:07
Show Gist options
  • Save piaoapiao/4662599 to your computer and use it in GitHub Desktop.
Save piaoapiao/4662599 to your computer and use it in GitHub Desktop.
semaphore test
- (void)viewDidLoad
{
[super viewDidLoad];
semaphoreTest = dispatch_semaphore_create(2);
[NSThread detachNewThreadSelector:@selector(workThread) toTarget:self withObject:nil];
[NSThread detachNewThreadSelector:@selector(workThread2) toTarget:self withObject:nil];
[NSThread detachNewThreadSelector:@selector(workThread3) toTarget:self withObject:nil];
UIButton *text = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 50, 30)];
text.backgroundColor = [UIColor redColor];
[text addTarget:self action:@selector(testSemaphore) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:text];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)testSemaphore
{
dispatch_semaphore_signal(semaphoreTest);
}
-(void)workThread
{
NSLog(@"begin1");
int i = dispatch_semaphore_wait(semaphoreTest, dispatch_time(DISPATCH_TIME_NOW ,10000000000000));
i ?NSLog(@"1time out"):NSLog(@"1successed");
}
-(void)workThread2
{
NSLog(@"begin2");
int i = dispatch_semaphore_wait(semaphoreTest, dispatch_time(DISPATCH_TIME_NOW ,10000000000000));
i ?NSLog(@"2time out"):NSLog(@"2successed");
}
-(void)workThread3
{
NSLog(@"begin3");
int i = dispatch_semaphore_wait(semaphoreTest, dispatch_time(DISPATCH_TIME_NOW ,10000000000000));
i ?NSLog(@"3time out"):NSLog(@"3successed");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment