新建一个view-based application,
viewcontroller.h的代码如下:
#import <UIKit/UIKit.h>
@interface tConditionViewController : UIViewController {
int tickets;
NSThread *t1;
NSThread *t2;
NSCondition *tc;
}
-(void)doSomething:(id)tname;
@end
viewcontroller.m的代码如下:
#import "tConditionViewController.h"
@implementation tConditionViewController
-(void)doSomething:(id)tname
{
NSString *name = (NSString *)tname;
while (TRUE) {
NSLog(@"in thread %@", name);
[NSThread sleepForTimeInterval:1];
[tc lock];
NSLog(@"kkkk");
[tc unlock];
}
}
- (void)dealloc
{
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
tc = [[NSCondition alloc] init];
t1 = [[NSThread alloc] initWithTarget:self selector:@selector(doSomething:) object:@"1"];
[t1 start];
t2 = [[NSThread alloc] initWithTarget:self selector:@selector(doSomething:) object:@"2"];
[t2 start];
[super viewDidLoad];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
@end
本文通过一个简单的例子展示了在iOS应用中如何使用NSCondition进行线程间同步。创建了一个view-based application,定义了一个tConditionViewController类,其中包含一个NSCondition实例tc,以及两个线程t1和t2。线程t1和t2分别调用doSomething:方法,在方法内部使用NSCondition进行加锁和解锁操作,确保线程安全。在viewDidLoad方法中初始化了线程和NSCondition,并启动线程。这个例子演示了如何在多线程环境中利用条件锁协调线程执行。
1172

被折叠的 条评论
为什么被折叠?



