我不是说同步之类的东西。实际上,这通常不是良好的编程习惯。我只是觉得有些事情应该做。
例如,假设我有一个线程会自行挂起并等待事件发生。通常事件发生在该线程挂起之前。
所以我希望事件等到线程在它发生之前挂起。
我怎么做?
例如,假设我想在 mainQueue 上做 5 件事。
做一点事。等到完成,下一步。
然后我这样做:
-(void) vDoSomeStuffsInSequence:(NSArray *) arblArrayOfBlocksToExecuteOnMainThread
{
if (self.blockThis) {
PO(@"Cancel Push View Controller");
return;
}
@synchronized(self)
{
self.blockThis=true;
}
AssertMainThread
NSMutableArray * arblNotFirstBlocks = [arblArrayOfBlocksToExecuteOnMainThread mutableCopy];
void(^blockToExecute)() = arblNotFirstBlocks[0];//execute first block right away
blockToExecute();
PO(@"execute pop push etc");
[arblNotFirstBlocks removeObjectAtIndex:0];
[[NSOperationQueue new] addOperationWithBlock:^{
PO(@"before first suspend");
[self vSuspendAndHaltThisThreadTillUnsuspended]; //This often happen after (instead of before) the code that execute [self vContinue is called]
PO(@"after first suspend");
for (void(^blockToExecute)() in arblNotFirstBlocks) {
while(false);
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
blockToExecute();//dothisfirst must unsuspend a thread somewhere
}];
[self vSuspendAndHaltThisThreadTillUnsuspended];
}
[[NSOperationQueue mainQueue]addOperationWithBlock:^{
@synchronized(self)
{
self.blockThis=false;
}
[self vContinue];
}];
[self vSuspendAndHaltThisThreadTillUnsuspended];
PO(@"finish vDoSomeStuffsInSequence");
}];
}