我有问题......
我需要这个:
创建一个新线程并暂停它(等待来自MainThread的通知)。 在MainThread中拉一个触发器来恢复这个后台线程。
在MainThread中:
[NSThread detachNewThreadSelector:@selector(startTheBackgroundJob:) toTarget:self withObject:nil];
在后台主题中:
- (void) startTheBackgroundJob {
@autoreleasepool {
NSLog(@"+ Thread %@ started and waiting.", self.identifier);
// Pause Here
NSLog(@"- Thread %@ unlocked", self.identifier);
[Scheduler doneTransaction: self];
}
}
MainThread:
- (void) unlock {
// resume a background thread
}
我尝试过NSLock,NSConditionLock和Semaphore GCD ......
答案 0 :(得分:0)
您可以做的一件事是将后台线程放在while循环中。一旦主线程到达允许后台线程继续的位置,您只需将后台线程踢出while循环。例如:
...
self.stayInLoop = YES; // BOOL in header - initialized before your thread starts
...
- (void)startTheBackgroundJob {
while (stayInLoop) {
// here your background thread stays in this loop (waits) until you
// change the flag
}
// more background thread code to be executed after breaking out of the loop
}
- (void)unlock {
self.stayInLoop = NO;
}
答案 1 :(得分:0)
这是您需要使用 NSCondition 对象时的经典场景。线程需要等到某些条件为真,因此您可以使用 lock , wait 和 signal 来实现此目的:
[sharedCondition lock];
while(!go)
{
[sharedCondition wait];
}
[sharedCondition unlock];
要通知线程,您应该发出信号:
[sharedCondition lock];
go= YES;
[sharedCondition signal];
[sharedCondition unlock];