我正在使用+ (BOOL)setThreadPriority:(double)p;更改NSThread的优先级,但是threadPriority始终为0.5。 setThreadPriority:的返回值为TURE

_thread =  [[NSThread alloc] initWithTarget:self selector:@selector(runThread) object:nil];

-(void)runThread {
    @autoreleasepool {
        [[NSThread currentThread] setName:@"3DF7EF974A80"];
        NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
        [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
        [_condition lock];
        [_condition signal];
        [_condition unlock];
        [NSThread setThreadPriority:1.0];
        CFRunLoopRun();

        [runLoop removePort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
        [_condition lock];
        [_condition signal];
        [_condition unlock];
    }
}


我正在使用Xcode 7.0.1和OS X 10.10.5。

最佳答案

我无法重现您描述的行为。当我在iOS或Mac OS X上执行以下操作时,它可以正确设置线程优先级:

@interface ViewController ()
{
    NSThread *_thread;
    NSCondition *_condition;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    _condition = [[NSCondition alloc] init];
    _thread = [[NSThread alloc] initWithTarget:self selector:@selector(runThread) object:nil];
    [_thread start];
    [self performSelector:@selector(checkThreadStatus) onThread:_thread withObject:nil waitUntilDone:false];
}

- (void)checkThreadStatus {
    NSLog(@"%.2f", [[NSThread currentThread] threadPriority]);
}

- (void)runThread {
    @autoreleasepool {
        [[NSThread currentThread] setName:@"3DF7EF974A80"];
        NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
        [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
        [_condition lock];
        [_condition signal];
        [_condition unlock];
        [NSThread setThreadPriority:1.0];
        CFRunLoopRun();

        [runLoop removePort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
        [_condition lock];
        [_condition signal];
        [_condition unlock];
    }
}

@end


我们需要minimal, yet reproducible, example of the problem来帮助您进一步诊断。

10-08 12:35