Я новичок в программировании на Objective C.
Я создал две темы с именем add и display с помощью NSInvocationOperation
и добавил его к NSOperationQueue
.
Сначала я запускаю поток отображения, а затем запускаю поток добавления. Поток дисплея после печати «Welcome to display» должен ждать результатов печати из метода add.
Итак, я установил метод waitUntilFinished
.
Обе операции находятся в одной очереди. Если я использую waitUntilFinished
для операций в той же очереди, может возникнуть ситуация, когда может произойти тупик (из документации разработчика Apple). Это так?
Для ожидания определенного интервала времени существует метод, называемый waitUntilDate:
Но если мне нужно это wait(min(100,dmax));
let dmax = 20;
Как мне ждать этих условий?
Было бы очень полезно, если бы кто-нибудь мог объяснить примером.
РЕДАКТИРОВАНИЕ:
threadss.h
------------
#import <Foundation/Foundation.h>
@interface threadss : NSObject {
BOOL m_bRunThread;
int a,b,c;
NSOperationQueue* queue;
NSInvocationOperation* operation;
NSInvocationOperation* operation1;
NSConditionLock* theConditionLock;
}
-(void)Thread;
-(void)add;
-(void)display;
@end
threadss.m
------------
#import "threadss.h"
@implementation threadss
-(id)init
{
if (self = [super init]) {
queue = [[NSOperationQueue alloc]init];
operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(display) object:nil];
operation1 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(add) object:nil];
theConditionLock = [[NSConditionLock alloc]init];
}
return self;
}
-(void)Thread
{
m_bRunThread = YES;
//[operation addDependency:operation1];
if (m_bRunThread) {
[queue addOperation:operation];
}
//[operation addDependency:operation1];
[queue addOperation:operation1];
//[self performSelectorOnMainThread:@selector(display) withObject:nil waitUntilDone:YES];
//NSLog(@"I'm going to do the asynchronous communication btwn the threads!!");
//[self add];
//[operation addDependency:self];
sleep(1);
[queue release];
[operation release];
//[operation1 release];
}
-(void)add
{
NSLog(@"Going to add a and b!!");
a=1;
b=2;
c = a + b;
NSLog(@"Finished adding!!");
}
-(void)display
{
NSLog(@"Into the display method");
[operation1 waitUntilFinished];
NSLog(@"The Result is:%d",c);
}
@end
main.m
-------
#import <Foundation/Foundation.h>
#import "threadss.h"
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
threadss* thread = [[threadss alloc]init];
[thread Thread];
[pool drain];
return 0;
}
Это то, что я пробовал с примером программы.
выход
2011-06-03 19:40:47.898 threads_NSOperationQueue[3812:1503] Going to add a and b!!
2011-06-03 19:40:47.898 threads_NSOperationQueue[3812:1303] Into the display method
2011-06-03 19:40:47.902 threads_NSOperationQueue[3812:1503] Finished adding!!
2011-06-03 19:40:47.904 threads_NSOperationQueue[3812:1303] The Result is:3
Является ли способ вызова потока правильным.
1. Будут ли какие-либо тупики?
2. Как сделать ожидание (мин (100, дмакс)), где дмакс = 50.