ios - NSThread sleepfortimeinterval 阻塞主线程

标签 ios nsthread

我想模拟与服务器的通信。由于远程服务器会有一些延迟,我想使用它上面的后台线程

 [NSThread sleepForTimeInterval:timeoutTillAnswer];

线程是使用 NSThread 子类创建并启动的……但是我注意到 sleepForTimeInterval 正在阻塞主线程……为什么???默认情况下 NSThread 不是 backgroundThread 吗?

线程是这样创建的:

   self.botThread = [[PSBotThread alloc] init];
    [self.botThread start];

更多信息: 这是机器人线程子类

- (void)main
{
    @autoreleasepool {
        self.gManager = [[PSGameManager alloc] init];
        self.comManager = [[PSComManager alloc] init];
        self.bot = [[PSBotPlayer alloc] initWithName:@"Botus" andXP:[NSNumber numberWithInteger:1500]];
        self.gManager.localPlayer = self.bot;
        self.gManager.comDelegate = self.comManager;
        self.gManager.tillTheEndGame = NO;
        self.gManager.localDelegate = self.bot;
        self.comManager.gameManDelegate = self.gManager;
        self.comManager.isBackgroundThread = YES;
        self.comManager.logginEnabled = NO;
        self.gManager.logginEnabled = NO;
        self.bot.gameDelegate = self.gManager;
        BOOL isAlive = YES;
        // set up a run loop
        NSRunLoop *runloop = [NSRunLoop currentRunLoop];
        [runloop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
        [self.gManager beginGameSP];
        while (isAlive) { // 'isAlive' is a variable that is used to control the thread existence...
            [runloop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        }



    }
}

- (void)messageForBot:(NSData *)msg
{
    [self.comManager didReceiveMessage:msg];
}

我想从主线程调用“messageForBot”……后台线程也应该在主线程上调用一个方法来进行通信……gManager 对象内部的 sleep 时间间隔……

最佳答案

它会阻塞运行 sleepForTimeInterval 的任何线程。在另一个线程上运行它以模拟您的服务器延迟,如下所示:

dispatch_queue_t serverDelaySimulationThread = dispatch_queue_create("com.xxx.serverDelay", nil);
dispatch_async(serverDelaySimulationThread, ^{
     [NSThread sleepForTimeInterval:10.0];
     dispatch_async(dispatch_get_main_queue(), ^{
            //Your server communication code here
    }); 
});

关于ios - NSThread sleepfortimeinterval 阻塞主线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18249749/

相关文章:

iphone - 无法在委托(delegate)方法中更改 UIButton 文本颜色

ios - 苹果 watch 可以打电话吗?

ios - Sprite 动画在 Cocos2d 中的 NSThread 方法中不起作用

iphone - UIProgressView 进度未更新

ios - NSManagedObjectContext中的NSOperation解除分配崩溃

ios - 我正在尝试使用 AVAudioPlayer 从服务器播放音频,但文件未播放

ios - 验证到应用程序商店。无效的代码签名权利。云端

ios - 验证失败时防止光标移动

iPhone:一个对象,一个线程

cocoa - 检测 cocoa 线程中的泄漏?