【问题标题】:po [NSThread currentThread]po [NSThread 当前线程]
【发布时间】:2011-11-20 08:33:44
【问题描述】:

当我执行 po [NSThread currentThread] 时,我得到了

{name = (null), num = 4}

当我向左看时,我看到:

看起来是 6 号线程,而不是 4 号。另外,我们还需要调用哪些属性来获取该线程号?

[NSThread currentThread].number?不过不存在。

【问题讨论】:

  • 我发现(lldb) thread info 更有用。您可以使用tid 将 Console.app / NSLog 的输出连接回线程。 thread #9: tid = 0x2e77, 0x0000000105293c9c

标签: objective-c xcode nsthread


【解决方案1】:

线程数几乎没有意义。

但是,线程实例是每个线程的单例。巧合的是,您可以使用 NSThread 的地址。更好的办法是深入到 mach_* API 并从该 API 中获取线程 ID。

[NSThread currentThread] 与您将获得的数字一样独特。如果线程终止,然后创建了一个新线程,您可能会看到出售的相同地址。 mach API 将提供一些非常独特的东西,真的。

你想做什么?

【讨论】:

  • 如果你需要每个线程的数据,我想你想要的是-[NSThread threadDictionary],或者(在较低级别)pthread_getspecific()/pthread_setspecific()
  • 是的——如果你想要每个线程的数据,这就是你要走的路。如果您尝试唯一标识一个线程,我可能会建议生成一个 UUID 并将其粘贴在线程的字典中。这样,当一个线程退出并创建一个新线程时,就不会有冲突的风险。
【解决方案2】:

对于 Swift 5: 它是一个私有变量,但可以使用 keypath 直接访问:

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

【讨论】:

    【解决方案3】:

    这是我发给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
    

    【讨论】:

    • 警告:似乎在 iOS8 中“num”已经变成了“number”(并且“number”和“name”已经交换了顺序......虽然上面的代码很好)
    • 没用的答案,这个方法只是解析[NSThread描述]并提取“数字”值,@Jim Thio的问题完全不同
    • @DaveOwens 谢谢,我改变了 sn-p
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 2011-09-21
    • 1970-01-01
    • 2012-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多