我有两个方法,每个都在不同的线程上。
当Method1处于关键阶段时,Method2需要等待。请注意,Method2会持续运行,仅当Method1在其临界区上运行时才需要等待。否则,请继续它的工作..
我该怎么做?
伪代码:
Method1
{
Announce the entrence to critical-section
......Do some stuff.........
Announce the leaving of critical-section
}
Method2
{
Method1 is in its critical-section? - WAIT TILL IT DONE
......Do some stuff...........
}发布于 2011-12-27 10:51:04
您应该使用条件变量来可靠地控制两个线程之间的行为。从技术上讲,你可以像其他答案建议的那样,只共享一个变量,但在其他情况下,它会很快崩溃。
BOOL isMethod1Busy = NO;
NSCondition *method1Condition = [[NSCondition alloc] init]
- (void)method1
{
[method1Condition lock];
isMethod1Busy = YES;
// do work
isMethod1Busy = NO;
[method1Condition signal];
[method1Condition unlock];
}
- (void)method2
{
[method1Condition lock];
while (isMethod1Busy) {
[method1Condition wait];
}
// do stuff while method1 is not working
[method1Condition unlock];
}发布于 2011-12-27 10:20:25
除了注意到在架构上,你可能应该设计你的软件是基于事件的,而不是你在这里已经有的,我假设你可以使用NSNotificationCenter来做Method1中的“公告”部分。
你可以做的另一件事,上面的警告,是在实例上设置一个BOOL,告诉它应该跳过处理:
-(void)method2 {
if (self.skipProcessing)
return;
//normal code here..
}发布于 2011-12-27 10:22:22
您应该使用某个共享变量(在逻辑上位于两个方法之上的某个位置)来同步两个方法。
在这里,我假设您正在使用像NSThread这样的东西来处理线程。
- (void)Method1:
{
self.SYNC_LOCK = YES;
// do some stuff
self.SYNC_LOCK = NO;
}
- (void)Method2:
{
if (self.SYNC_LOCK) {return;}
// do some stuff
}如果你也在寻找一个简单的线程库,你应该看看中央调度中心。我有一个库(GCD - GitHub),它很好地包装了这些东西。
- (void)Method1
{
[GCD doInBackground: ^{
self.SYNC_LOCK = YES;
// do some stuff
self.SYNC_LOCK = NO;
}];
}
- (void)Method2
{
void (^stuff_block)(void) = ^{
while (!self.SYNC_LOCK) {sleep(SOME_WAIT_TIME);}
//do some stuff
};
[GCD doInBackground: stuff_block every: FEW_SECONDS];
}https://stackoverflow.com/questions/8640590
复制相似问题