Search code examples
objective-cmacoscocoansthread

NSThread setThreadPriority: is not working


I am using + (BOOL)setThreadPriority:(double)p; to change priority of NSThread but threadPriority is always 0.5. Return value of setThreadPriority: is 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];
    }
}

I am using Xcode 7.0.1 and OS X 10.10.5.


Solution

  • I cannot reproduce the behavior you describe. When I do the following on either iOS or Mac OS X, it correctly sets the thread priority:

    @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
    

    We need minimal, yet reproducible, example of the problem in order to help you diagnose this further.