在iphone上多线程开发有两种方式。一是用pthread开发,别一种是cocoa中的NSThread。本示例展示NSThread的方法,一切以代码说话:
// main.m // // Created by Christopher Wright on 2007.06.12. #import <Foundation/Foundation.h> NSLock *lock; @interface MyObject : NSObject +(void)aMethod:(id)param; @end @implementation MyObject +(void)aMethod:(id)param{ int x; for(x=0;x<50;++x) { [lock lock]; printf("Object Thread says x is %i/n",x); usleep(1); [lock unlock]; } } @end int main(int argc, char *argv[]) { int x; lock = [[NSLock alloc] init]; [NSThread detachNewThreadSelector:@selector(aMethod:) toTarget:[MyObject class] withObject:nil]; for(x=0;x<50;++x) { [lock lock]; printf("Main thread says x is %i/n",x); usleep(10000); printf("Main thread lets go/n",x); [lock unlock]; usleep(100); } return 0; }