-1

我不是说同步之类的东西。实际上,这通常不是良好的编程习惯。我只是觉得有些事情应该做。

例如,假设我有一个线程会自行挂起并等待事件发生。通常事件发生在该线程挂起之前。

所以我希望事件等到线程在它发生之前挂起。

我怎么做?

例如,假设我想在 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");
    }];
}
4

2 回答 2

2

Polling, waiting, and long or indefinite thread or resource blocking are generally best avoided. Nevertheless... you can wait using condition variables, dispatch_group_wait, or -[NSOperationQueue waitUntilAllOperationsAreFinished].

于 2013-05-14T03:28:53.847 回答
2

What you are describing is a well-known race condition that arises in many event-delivery systems, and the solution depends on the details of the system's programming interface.

For example, detecting a Unix signal is prone to this race condition, and there are a number of solutions (of varying portability). See “Handling Signals” on the Event Loop Wikipedia page for a couple of them.

So the answer to your question depends entirely on what events you want to detect and the programming interfaces available to detect them. You need to edit your post to include those details if you want a more specific answer.

于 2013-05-14T03:20:12.267 回答