自学内容网 自学内容网

prctl的函数和pthread_self函数

1.prctl的函数原型如下:

#include<sys/prctl.h>
​prctl(PR_SET_NAME, “process_name”);

第一个参数是操作类型,指定PR_SET_NAME(对应数字15),即设置进程名;
第二个参数是进程名字符串,长度至多16字节。

#include<stdio.h>
#include<pthread.h>
#include<sys/prctl.h>
  
void* test(void*arg)
{
    char name[32];
    prctl(PR_SET_NAME,(unsignedlong)"xx");
    prctl(PR_GET_NAME,(unsignedlong)name);
    printf("%s/n", name);
    while(1)
    sleep(1);
} 
 
int main(void)
{
    pthread_t tid;
    pthread_create(&tid,NULL,test,NULL);
    pthread_join(tid,NULL);
    return 0;
}

可以看到打印出的线程名字为xx,进程和线程的ID号不同。

====================================

2.pthread_self函数

pthread_self() 函数是 POSIX 线程库的一部分,它提供了一个非常简单的功能:获取当前线程的唯一标识符。这个标识符是 pthread_t 类型的,通常是一个无符号的长整型值,不过具体的类型是由实现定义的,这意味着它可以在不同的操作系统上有不同的表示。

这个标识符对于调试多线程程序非常有用,因为可以以此来区分哪个线程正在执行。此外,pthread_self() 在实现线程的同步操作时也很有用,例如,在一个线程中设置一个锁,并且只允许拥有这个锁的线程来释放它。

pthread_self() 函数的原型如下:

#include <pthread.h>
pthread_t pthread_self(void);

在多线程程序中,每个线程都可以通过调用 pthread_self() 来获取自己的线程ID。线程ID可以用于比较操作,以判断两个线程ID是否相同。


原文地址:https://blog.csdn.net/weixin_44651073/article/details/142743595

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!