iphone 线程同步和锁 NSCondition

来源:互联网 发布:数据挖掘 r语言实战 编辑:程序博客网 时间:2024/05/29 15:53

 

 

以下代码,为网上下载的程序,忘记哪里下载了

.h

#import <UIKit/UIKit.h>

@interface ConditionViewController : UIViewController
{
 UILabel *m_label;
 NSCondition *m_Condition;
 
 BOOL m_bPause;
 BOOL m_bExit;
}

@end

 

.m

#import "ConditionViewController.h"

@implementation ConditionViewController

 

/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/


// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
 [super loadView];
 CGRect rcLabel = CGRectMake(0, (480 - 40)/2, 320, 40);
 m_label = [[UILabel alloc] initWithFrame:rcLabel];
 m_label.textAlignment = UITextAlignmentCenter;
 [self.view addSubview:m_label];
 [m_label release];

 CGRect rcExitBtn = CGRectMake(0, CGRectGetMaxY(rcLabel), 100, 40);
 UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
 btn.frame = rcExitBtn;
 [btn setTitle:@"线程退出" forState:UIControlStateNormal];
 [btn addTarget:self action:@selector(threadExtiNotify) forControlEvents:UIControlEventTouchUpInside];
 [self.view addSubview:btn];
 
 CGRect rcPauseBtn = CGRectMake(CGRectGetMaxX(rcExitBtn), CGRectGetMaxY(rcLabel), 100, 40);
 UIButton *pauseBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
 pauseBtn.frame = rcPauseBtn;
 [pauseBtn setTitle:@"线程暂停" forState:UIControlStateNormal];
 [pauseBtn addTarget:self action:@selector(threadPauseNotify) forControlEvents:UIControlEventTouchUpInside];
 [self.view addSubview:pauseBtn];
 
 
 CGRect rcResume = CGRectMake(CGRectGetMaxX(rcPauseBtn), CGRectGetMaxY(rcLabel), 100, 40);
 UIButton *rcResumeBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
 rcResumeBtn.frame = rcResume;
 [rcResumeBtn setTitle:@"线程恢复" forState:UIControlStateNormal];
 [rcResumeBtn addTarget:self action:@selector(threadResumeNotify) forControlEvents:UIControlEventTouchUpInside];
 [self.view addSubview:rcResumeBtn];
 
 m_Condition = [[NSCondition alloc] init];
 [NSThread detachNewThreadSelector:@selector(threadFun) toTarget:self withObject:nil];
}


-(void)threadFun
{
 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
 int i = 1;
 
 while (YES)
 {
  [m_Condition lock];
  if(m_bPause)
  {
   [m_Condition wait];
  }
  else
  {

//+ (id)dateWithTimeIntervalSinceNow:(NSTimeInterval)secs;     typedef double NSTimeInterval;  等待时间为double

   [m_Condition waitUntilDate:[NSDate  dateWithTimeIntervalSinceNow:2]];
  }

  [m_Condition unlock];
  
  [m_Condition lock];
  if(!m_bExit)
  {
   [m_Condition unlock];
   if(!m_bPause)//如果没有暂停线程就继续刷新
   {
    [self performSelectorOnMainThread:@selector(refleshLabel:) withObject:[NSNumber numberWithInt:i] waitUntilDone:NO];//改变界面显示,估计必须在主线程中才可以

    i++;
   }
  }
  else
  {
   [m_Condition unlock];
   break;
  }
 }
 [self performSelectorOnMainThread:@selector(refleshLabelByThreadExit) withObject:nil waitUntilDone:NO];//改变界面显示,估计必须在主线程中才可以
 [pool release];
}

-(void)refleshLabel:(NSNumber*)num;
{
 
 m_label.text = [NSString stringWithFormat:@"平均2秒刷新一次,现在是第%d次", [num intValue]];
}

-(void)refleshLabelByThreadExit
{
 m_label.text = @"线程退出";
}

//线程退出通知
-(void)threadExtiNotify
{
 [m_Condition lock];
 m_bExit = YES;
 [m_Condition signal];//防止线程在暂停状态,所以加这个
 [m_Condition unlock];
}

//线程暂停通知
-(void)threadPauseNotify
{
 [m_Condition lock];
 if(!m_bPause)
 {
  m_bPause = YES;
 }
 [m_Condition unlock]; 
}

 

//线程暂停之后,恢复运行

-(void)threadResumeNotify
{
 [m_Condition lock];
 if(m_bPause)
 {
  m_bPause = NO;
  [m_Condition signal]; //[m_Condition wait] 等的就是这个 signal
 }
 [m_Condition unlock]; 
}
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (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.
}

- (void)viewDidUnload {
 // Release any retained subviews of the main view.
 // e.g. self.myOutlet = nil;
}


- (void)dealloc {
 [m_Condition release];
    [super dealloc];
}

@end

 

 

原创粉丝点击