我可以从pthread_self()获取线程的堆栈地址吗 [英] Can I get a thread's stack address from pthread_self()

查看:68
本文介绍了我可以从pthread_self()获取线程的堆栈地址吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过某些函数获取线程的堆栈地址,我们可以将 pthread_self()传递给该函数.是否可以?我这样做的原因是因为我想为自己在堆栈中某个位置的线程编写分配的线程标识符.我可以在堆栈末尾附近写(堆栈末尾而不是当前堆栈地址.我们当然可以期望应用程序不会到达堆栈底部,因此要从那里开始使用空间.)

I want to get the stack address of a thread through some function to which we can pass pthread_self(). Is it possible? The reason I am doing this is because I want to write my own assigned thread identifier for a thread somewhere in its stack. I can write near the end of the stack (end of the stack memory and not the current stack address. We can ofcourse expect the application to not get to the bottom of the stack and therefore use space from there).

换句话说,我想使用线程堆栈在其中放置一种线程局部变量.那么,我们是否具有pthread提供的类似于以下功能的功能?

In other words, I want to use the thread stack for putting a kind of thread local variable there. So, do we have some function like the following provided by pthread?

stack_address = stack_address_for_thread( pthread_self() );

为此,我可以使用gcc对线程局部变量使用语法,但是我处于无法使用它们的情况.

I can use the syntax for thread local variables by gcc for this purpose, but I'm in a situation where I can't use them.

推荐答案

首先使用下面的代码获取栈的底部并对栈授予读/写权限.

First get the bottom of the stack and give read/write permission to it with the following code.

pthread_attr_t attr;
void * stackaddr;
int * plocal_var;
size_t stacksize;

pthread_getattr_np(pthread_self(), &attr);
pthread_attr_getstack( &attr, &stackaddr, &stacksize );

printf( "stackaddr = %p, stacksize = %d\n", stackaddr, stacksize );

plocal_var = (int*)mmap( stackaddr, 4096, PROT_READ | PROT_WRITE, 
          MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0 );
// Now try to write something 
*plocal_var = 4;

,然后可以使用下面显示的函数 get_thread_id()获取线程ID.请注意,调用大小为4096的 mmap 的作用是将堆栈的边界推4096,这就是为什么我们在获取局部变量地址时减去4096.

and then you can get the thread ID, with the function get_thread_id() shown below. Note that calling mmap with size 4096 has the effect of pushing the boundary of the stack by 4096, that is why we subtract 4096 when getting the local variable address.

int get_thread_id()
{
    pthread_attr_t attr;
    char * stackaddr;
    int * plocal_var;
    size_t stacksize;

    pthread_getattr_np(pthread_self(), &attr);
    pthread_attr_getstack( &attr, (void**)&stackaddr, &stacksize );

    //printf( "stackaddr = %p, stacksize = %d\n", stackaddr, stacksize );

    plocal_var = (int*)(stackaddr - 4096);

    return *plocal_var;
}

这篇关于我可以从pthread_self()获取线程的堆栈地址吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆