我有 2 个方法,每个方法都在不同的线程上。
当方法 1 处于临界区时,方法 2 需要等待。 请注意,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...........
}
最佳答案
您应该使用条件变量来可靠地控制两个线程之间的行为。从技术上讲,您可以通过共享变量来执行其他答案所建议的操作,但在其他情况下它会很快崩溃。
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];
}
关于iphone - 在 Objective C 中同步 2 个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8640590/