我是靠谱客的博主 爱笑小鸭子,最近开发中收集的这篇文章主要介绍prctl函数设置线程别名prctl函数用法,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

prctl函数用法

NAME
prctl - operations on a process
SYNOPSIS
#include <sys/prctl.h>
int prctl(int option, unsigned long arg2, unsigned long arg3,
unsigned long arg4, unsigned long arg5);
DESCRIPTION
prctl()
is
called with a first argument describing what to do (with values defined in <linux/prctl.h>), and further arguments with a significance
depending on the first one.
The first argument can be:
PR_SET_NAME (since Linux 2.6.9)
Set the name of the calling thread, using the value in the location pointed to by (char *) arg2.
The name can be up to 16 bytes
long,
and should
be
null-terminated
if it contains fewer bytes.
This is the same attribute that can be set via pthread_setname_np(3) and retrieved using pthread_getname_np(3).
The attribute is likewise accessible via /proc/self/task/[tid]/comm, where tid is
the
name
of
the
calling thread.
PR_GET_NAME (since Linux 2.6.11)
Return
the
name
of
the calling thread, in the buffer pointed to by (char *) arg2.
The buffer should allow space for up to 16 bytes; the returned string will be null-terminated if it is shorter than that.

示例代码

#include <iostream>
#include <unistd.h>
#include <thread>
#include <vector>
#include <sys/prctl.h>
// PR_SET_NAME
inline void SetThreadName(const std::string& name)
{
::prctl(PR_SET_NAME, name.c_str());
}
volatile bool g_is_running = false;
int main()
{
std::vector<std::thread*> thread_manager;
thread_manager.reserve(20);
g_is_running = true;
for (int i = 0; i < 10; i++)
{
thread_manager.emplace_back(new std::thread([&](){
SetThreadName("t-" + std::to_string(i));
while (g_is_running)
{
usleep(1);
}
}));
}
for (auto& thr : thread_manager)
{
thr->join();
}
return 0;
}

查看cpu使用情况

➜
~ top -H -p 10287
top - 23:35:22 up 235 days, 12:17,
2 users,
load average: 0.22, 0.11, 0.07
Threads:
11 total,
2 running,
9 sleeping,
0 stopped,
0 zombie
%Cpu(s):
4.3 us, 10.5 sy,
0.0 ni, 85.2 id,
0.0 wa,
0.0 hi,
0.0 si,
0.0 st
KiB Mem :
8008616 total,
175312 free,
625272 used,
7208032 buff/cache
KiB Swap:
0 total,
0 free,
0 used.
7068056 avail Mem
PID USER
PR
NI
VIRT
RES
SHR S %CPU %MEM
TIME+ COMMAND
10293 root
20
0
97904
1416
1212 S 17.6
0.0
0:10.94 t-6
10289 root
20
0
97904
1416
1212 S 17.3
0.0
0:10.95 t-2
10290 root
20
0
97904
1416
1212 S 17.3
0.0
0:10.91 t-4
10291 root
20
0
97904
1416
1212 S 17.3
0.0
0:10.93 t-4
10292 root
20
0
97904
1416
1212 R 17.3
0.0
0:10.94 t-5
10294 root
20
0
97904
1416
1212 S 17.3
0.0
0:10.92 t-7
10295 root
20
0
97904
1416
1212 R 17.3
0.0
0:10.92 t-8
10296 root
20
0
97904
1416
1212 S 17.3
0.0
0:10.92 t-9
10297 root
20
0
97904
1416
1212 S 17.3
0.0
0:10.89 t-10
10288 root
20
0
97904
1416
1212 S 16.9
0.0
0:10.92 t-1
10287 root
20
0
97904
1416
1212 S
0.0
0.0
0:00.00 app

最后

以上就是爱笑小鸭子为你收集整理的prctl函数设置线程别名prctl函数用法的全部内容,希望文章能够帮你解决prctl函数设置线程别名prctl函数用法所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(36)

评论列表共有 0 条评论

立即
投稿
返回
顶部