Skip to content

Instantly share code, notes, and snippets.

@minsOne
Last active August 29, 2015 14:05
Show Gist options
  • Select an option

  • Save minsOne/e502ab795ae812aa907a to your computer and use it in GitHub Desktop.

Select an option

Save minsOne/e502ab795ae812aa907a to your computer and use it in GitHub Desktop.
RaceCondition using GCD in Objective-C
/*
RaceCondition using GCD in Objective-C
localCountLabel and globalCountLabel increment 1, 5 through each Thread
*/
__block NSUInteger localCount1, localCount2, localCount3, globalCount;
UILabel *localCountLabel1, *localCountLabel2, *localCountLabel3, *globalCountLabel;
localCountLabel1 = [[UILabel alloc]init];
localCountLabel2 = [[UILabel alloc]init];
localCountLabel3 = [[UILabel alloc]init];
globalCountLabel = [[UILabel alloc]init];
localCount1 = localCount2 = localCount3 = globalCount = 0;
localCountLabel1.text = localCountLabel2.text = localCountLabel3.text = globalCountLabel.text = @"0";
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
while (true) {
localCount1++;
globalCount += 5;
NSLog(@"LocalCount1 Thread : %d %d", localCount1, globalCount);
dispatch_async(dispatch_get_main_queue(), ^{
localCountLabel1.text = [NSString stringWithFormat:@"localCount1 : %d", localCount1];
globalCountLabel.text = [NSString stringWithFormat:@"globalCount : %d", globalCount];
});
}
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
while (true) {
localCount2++;
globalCount += 5;
NSLog(@"LocalCount2 Thread : %d %d", localCount2, globalCount);
dispatch_async(dispatch_get_main_queue(), ^{
localCountLabel2.text = [NSString stringWithFormat:@"localCount2 : %d", localCount2];
globalCountLabel.text = [NSString stringWithFormat:@"globalCount : %d", globalCount];
});
}
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
while (true) {
localCount3++;
globalCount += 5;
NSLog(@"LocalCount3 Thread : %d %d", localCount3, globalCount);
dispatch_async(dispatch_get_main_queue(), ^{
localCountLabel3.text = [NSString stringWithFormat:@"localCount3 : %d", localCount3];
globalCountLabel.text = [NSString stringWithFormat:@"globalCount : %d", globalCount];
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment