https://blog.csdn.net/jasonchen_gbd/article/details/51308638
1 #define wtm_set_thread_name(n) ({ 2 char tname[THREAD_NAME_LEN + 1] = ""; 3 if (strlen(n) > THREAD_NAME_LEN) 4 log_debug("wtm_util_misc", "Thread name is too long, truncating it..."); 5 strlcpy(tname, n, THREAD_NAME_LEN); 6 int ret = 0; 7 if ((ret = prctl(PR_SET_NAME, tname, 0, 0, 0)) < 0) 8 log_debug("wtm_util_misc", "Error setting thread name "%s": %s", tname, strerror(errno)); 9 ret; 10 })
已上为自己的代码,下面为转载内容。
为了能方便的区分一个进程中的每个线程,可以通过prctl()给每个线程取个名字。这样在会创建多个线程的程序执行过程中,就能知道一个pid或tid对应的是哪个线程,对调试程序有一定帮助。
prctl是个系统调用,可以用来读取和更改一个线程的属性。其用户态接口定义如下:
1 #include <sys/prctl.h> 2 3 int prctl(int option, unsigned long arg2, unsigned long arg3, 4 unsigned long arg4, unsigned long arg5);
第一个参数option用来告诉prctl要对当前线程做什么操作,针对不同的操作,后面需要的参数个数也不同。其中用来获取和修改当前线程名字的option是下面两个:
PR_SET_NAME:设置当前线程的名字
PR_GET_NAME:获得当前线程的名字
这两个option都只需要一个参数,即用来存储线程名的字符串。
对于arg2有如下要求:
PR_SET_NAME:arg2存放将要设置的线程名的字符指针,即(char *)arg2。名字的长度最大为15字节,且应该以'