0

我有问题...

我需要这个:

创建一个新线程,并暂停它(等待来自 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];
    }
}

主线程:

- (void) unlock {
    // resume a background thread
}

我试过 NSLock、NSConditionLock 和 Semaphore GCD....

4

2 回答 2

0

这是您需要使用NSCondition对象时的经典场景。线程需要等待,直到某些条件为真,因此您可以使用lockwaitsignal来实现:

[sharedCondition lock];
while(!go)
{
    [sharedCondition wait];
}
[sharedCondition unlock];

要通知线程,您应该发出条件信号:

[sharedCondition lock];
go= YES;
[sharedCondition signal];
[sharedCondition unlock];
于 2013-07-05T23:07:24.057 回答
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;
}
于 2013-07-05T22:56:26.367 回答