开发者

po [NSThread currentThread]

开发者 https://www.devze.com 2023-04-06 10:18 出处:网络
When I do po [NSThread currentThread], I got {name = (null), num = 4} When I look to the left I see: Looks like it\'s Thread number 6, not开发者_JAVA技巧 4. Also what properties do we need to cal

When I do po [NSThread currentThread], I got

{name = (null), num = 4}

When I look to the left I see:

po [NSThread currentThread]

Looks like it's Thread number 6, not开发者_JAVA技巧 4. Also what properties do we need to call to get that thread numbers anyway?

[NSThread currentThread].number? Doesn't exist though.


Thread numbers are meaningless, pretty much.

The thread instance, though, is a singleton per thread. You could use the NSThread's address, by coincidence. Better, still, would be to dip down to the mach_* API and grab the thread ID from that API.

[NSThread currentThread] is about as unique of a number as you'll get. If the thread terminates and then a new thread is created, you might see the same address vended. The mach APIs will vend something just about as unique, really.

What are you trying to do?


For Swift 5: It's a private variable, but accessible directly using keypath:

Thread.current.value(forKeyPath: "private.seqNum")!


Here's the answer I posted to NSThread number on iOS?:


@implementation NSThread (ThreadGetIndex)

-(NSInteger)getThreadNum
{
    NSString * description = [ self description ] ;
    NSArray * keyValuePairs = [ description componentsSeparatedByString:@"," ] ;
    for( NSString * keyValuePair in keyValuePairs )
    {
        NSArray * components = [ keyValuePair componentsSeparatedByString:@"=" ] ;
        NSString * key = components[0] ;
        key = [ key stringByTrimmingCharactersInSet:[ NSCharacterSet whitespaceCharacterSet ] ] ;
        if ( [ key isEqualToString:@"number" ] || [ key isEqualToString:@"num" ] )
        {
            return [ components[1] integerValue ] ;
        }
    }
    @throw @"couldn't get thread num";
    return -1 ;
}

@end
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号