Linux 为线程设定名字

演示如下:


[root@shanghai c++11]# cat test1.c
#include <unistd.h>
#include <pthread.h>
#include <sys/prctl.h>

#include <stdio.h>

void* StartThreadEntry(void * arg)
{
    int loop = 60;
    printf("线程被调用:");
    char name[16];
    prctl(PR_SET_NAME, (char*)arg);
    prctl(PR_GET_NAME, (unsigned long)name);
    printf("%s\n", name);
    while (loop--)
    {
        sleep (1);
    }
    pthread_exit(NULL);
    return NULL;
}

int main(void)
{
    printf("进程ID:%d\n",getpid()) ;
    prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);  // 设置可ptrace

    pthread_t tid1;
    pthread_t tid2;
    pthread_t tid3;
    pthread_t tid4;

    pthread_create(&tid1, NULL, StartThreadEntry, "线程1");
    pthread_create(&tid2, NULL, StartThreadEntry, "线程2");
    pthread_create(&tid3, NULL, StartThreadEntry, "线程3");
    pthread_create(&tid4, NULL, StartThreadEntry, "线程4");

    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    pthread_join(tid3, NULL);
    pthread_join(tid4, NULL);

    return 0;
}
[root@shanghai c++11]#  gcc -Wall  test1.c -l pthread && ./a.out 
进程ID:12784
线程被调用:线程4
线程被调用:线程1
线程被调用:线程2
线程被调用:线程3
[root@shanghai c++11]# 

ps 查看所有的线程


[root@shanghai ~]# ps -eL
  PID   LWP TTY          TIME CMD
12784 12784 pts/1    00:00:00 a.out
12784 12785 pts/1    00:00:00 线程1
12784 12786 pts/1    00:00:00 线程2
12784 12787 pts/1    00:00:00 线程3
12784 12788 pts/1    00:00:00 线程4
12799 12799 pts/2    00:00:00 ps

top 查看线程资源占用方式


[root@shanghai ~]# top -H 
  PID USER      PR  NI    VIRT    RES    SHR S %CPU %MEM     TIME+ COMMAND                                                                                                  
12784 root      20   0   39244    380    296 S  0.0  0.0   0:00.00 a.out                                                                                                    
12785 root      20   0   39244    380    296 S  0.0  0.0   0:00.00 线程1                                                                                                   
12786 root      20   0   39244    380    296 S  0.0  0.0   0:00.00 线程2                                                                                                   
12787 root      20   0   39244    380    296 S  0.0  0.0   0:00.00 线程3                                                                                                   
12788 root      20   0   39244    380    296 S  0.0  0.0   0:00.00 线程4                                                                                                   
12814 root      20   0  157724   2200   1516 R  0.0  0.2   0:00.51 top                                                                                                      
28220 root      20   0  115512   2140   1672 S  0.0  0.2   0:00.02 bash          

猜你喜欢

转载自my.oschina.net/u/3776585/blog/1648295