关于多线程 runloop

来源:互联网 发布:微信支付网页授权域名 编辑:程序博客网 时间:2024/05/29 12:42

转载自:http://zhidao.baidu.com/link?url=OBHY7DfISKCLvcUJC81rCCk5lBGn8D6lOSflNk6GK1Gf5hAAzekeBers-WtAeBRH7aAWsSyNJ1QxDZxi0mz7UGWcI8O4uiM18UWDvYLw8cu


NSThread *thread1 = [[NSThread alloc] initWithTarget:self

                                            selector:@selector(playerThread:)object:nil];

[thread start];

//如果要利用NSOperation,原理类似。只需要加入到queue里面去就好了。。queue会在合适的时机调用方法,下面代码作为参考。

- (void)playerThread:(void*)unused

{

    audioRunLoop = CFRunLoopGetCurrent();//子线程的runloop引用。

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];//子线程的run loop

    [self initPlayer];

    CFRunLoopRun(); //运行子线程的run loop,这里就会停住了。

    [pool release];

} // 实现一个timer,用于检查子线程的工作状态,并在合适的时候做任务切换。或者是合适的时候停掉自己的run loop

-(void)initPlayer

{        // 在这里你可以初始化一个工作类。比如声音或者视频播放。

    NSTimer *stateChange = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(checkState:) userInfo:nil repeats:YES];

}

-(void)checkState:(NSTimer*) timer

{

    if(需要退出自线程了)

    {   //释放子线程里面的资源。

        CFRunLoopStop( CFRunLoopGetCurrent());//结束子线程任务

    }

}

0 0
原创粉丝点击