NSCondition的用法
使用NSCondition,实现多线程的同步,即,可实现生产者消费者问题。
基本思路是,首先要创建公用的NSCondition实例。然后:
- 消费者取得锁,取产品,如果没有,则wait,这时会释放锁,直到有线程唤醒它去消费产品;
- 生产者制造产品,首先也是要取得锁,然后生产,再发signal,这样可唤醒wait的消费者。
- ( IBAction )conditionTest:( id )sender { NSLog (@ "begin condition works!" ); products = [[ NSMutableArray alloc] init]; condition = [[ NSCondition alloc] init]; [ NSThread detachNewThreadSelector: @selector (createProducter) toTarget: self withObject: nil ]; [ NSThread detachNewThreadSelector: @selector (createConsumenr) toTarget: self withObject: nil ]; } - ( void )createConsumenr { [condition lock]; while ([products count] == 0) { NSLog (@ "wait for products" ); [condition wait]; } [products removeObjectAtIndex:0]; NSLog (@ "comsume a product" ); [condition unlock]; } - ( void )createProducter { [condition lock]; [products addObject:[[ NSObject alloc] init]]; NSLog (@ "produce a product" ); [condition signal]; [condition unlock]; } |
这样就可以通过创建两个子线程,使用操作系统的信号变量 实现线程同步, 代码如上所示!