【问题标题】:How to get a pthread name in C如何在 C 中获取 pthread 名称
【发布时间】:2020-05-02 07:30:48
【问题描述】:

假设我创建了一个 pthread 为 pthread_t lift_3;pthread_create(&lift_1, NULL, lift, share);。当它进入lift() 时,如何获得打印线程实际名称的功能?还是给线程起个名字?

我曾尝试使用pthread_self() 来获取 id,但它却给出了随机数

#include <stdio.h> 
#include <stdlib.h> 
#include <pthread.h> 
void* lift(void* ptr) 
{ 
    printf("thread name = %c\n", pthread_self()); 
    pthread_exit(NULL); 
    return NULL; 
} 

int main() 
{ 
    pthread_t lift_1; // declare thread 
    pthread_create(&lift_1, NULL, lift, NULL); 
    pthread_join(lift_1, NULL);  
    return 0; 
} 

预期的结果应该是thread name = lift_1

【问题讨论】:

标签: c pthreads


【解决方案1】:

您正在寻找“线程开始的函数的名称”。 没有“线程名称”之类的东西。 调用pthread_self 时,您会得到线程的“id”,它类似于随机生成的名称。

为了模拟过去想要的行为,我写了如下代码:

#include <stdio.h> 
#include <stdlib.h> 
#include <pthread.h> 

// This lines means a variable that is created per-thread
__thread const char* thread_name;

void* lift(void* ptr) 
{ 
    // Paste this line in the beginning of every thread routine.
    thread_name = __FUNCTION__;

    // Note two changes in this line
    printf("thread name = %s\n", thread_name); 
    pthread_exit(NULL); 
    return NULL; 
} 

int main() 
{ 
    // Added line
    thread_name = __FUNCTION__;

    pthread_t lift_1; // declare thread 
    pthread_create(&lift_1, NULL, lift, NULL); 
    pthread_join(lift_1, NULL);  
    //Added line
    printf("Original thread name: %s\n", thread_name);
    return 0; 
} 

【讨论】:

  • __FUNCTION__ 是一个 GNU 扩展,用于(非常旧的)向后兼容性。使用__func__
  • 该代码工作正常,但 thread_name 应该在 pthread_create 中作为参数而不是全局变量。
  • “没有“线程名”之类的东西”——在某些平台上,man7.org/linux/man-pages/man3/pthread_setname_np.3.html
  • 很高兴知道!公平地说,pthread_set_name 可能是使用我的解决方案实现的。
猜你喜欢
  • 2022-08-12
  • 2015-10-14
  • 2010-11-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多