关于posix的背景知识,请google之,也可以参考下面的链接:http://www.ibm.com/developerworks/cn/linux/theme/posix_thread/#secondmajorhead
由于本人的Mac book坏了,这个礼拜也没有好的希望,所以这里不解释过了,以后再编辑这个把。
创建一个view-based application,界面上加入一个label,一个button, viewcontroller的头文件如下:
#import <UIKit/UIKit.h>
@interface TPosixThreadViewController : UIViewController {
UILabel *myLabel;
}
@property (nonatomic, retain) IBOutlet UILabel *myLabel;
- (IBAction)start:(id)sender;
-(void)update;
@end
实现文件如下:
#import "TPosixThreadViewController.h"
#import <pthread.h>
void* PosixThreadMainRoutine(void* data)
{
TPosixThreadViewController *inputData = (TPosixThreadViewController *)data;
[inputData update];
// Do some work here.
NSLog(@"test posix thread");
return NULL;
}
@implementation TPosixThreadViewController
@synthesize myLabel;
- (void)dealloc
{
[myLabel release];
[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
{
[super viewDidLoad];
}
*/
- (void)viewDidUnload
{
[self setMyLabel:nil];
[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);
}
- (IBAction)start:(id)sender {
// Create the thread using POSIX routines.
pthread_attr_t attr;
pthread_t posixThreadID;
int returnVal;
returnVal = pthread_attr_init(&attr);
assert(!returnVal);
returnVal = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
assert(!returnVal);
pthread_attr_setstacksize(&attr, 1024*1024);
int threadError = pthread_create(&posixThreadID, &attr, &PosixThreadMainRoutine, self);
returnVal = pthread_attr_destroy(&attr);
assert(!returnVal);
if (threadError != 0)
{
// Report an error.
}
}
-(void)update
{
myLabel.text = @"kkkk";
}
@end