c - 读取另一个线程的寄存器或线程局部变量

标签 c linux x86-64

是否可以直接读取另一个线程的寄存器或线程局部变量,即不需要进入内核?这样做的最佳方法是什么?

最佳答案

您无法读取寄存器,这无论如何都没有用。但是从另一个线程读取线程局部变量是很容易的。

根据体系结构(例如 x86_64 上的强内存顺序),即使没有同步,您也可以安全地执行此操作,前提是读取值不会以任何方式影响线程所属的方式。一个场景是显示一个线程本地计数器或类似的。

特别是在你标记的 x86_64 上的 linux 中,你可以这样:

// A thread local variable. GCC extension, but since C++11 actually part of C++
__thread int some_tl_var;

// The pointer to thread local. In itself NOT thread local, as it will be
// read from the outside world.
struct thread_data {
    int *psome_tl_var;
    ...
};

// the function started by pthread_create. THe pointer needs to be initialized
// here, and NOT when the storage for the objects used by the thread is allocated
// (otherwise it would point to the thread local of the controlling thread)
void thread_run(void* pdata) {
    pdata->psome_tl_var = &some_tl_var;

    // Now do some work...
    // ...
}

void start_threads() {
    ...
    thread_data other_thread_data[NTHREADS];
    for (int i=0; i<NTHREADS; ++i) {
        pthread_create(pthreadid, NULL, thread_run, &other_thread_data[i]);       
    }

    // Now you can access each some_tl_var as
    int value = *(other_thread_data[i].psome_tl_var);
    ...
}

我使用 similar 来显示有关工作线程的一些统计信息。在 C++ 中甚至更容易,如果您围绕线程创建对象,只需将指向线程本地的指针设为线程类中的一个字段,并使用成员函数进行访问。

免责声明:这是不可移植的,但它可以在 x86_64、linux、gcc 上运行,也可以在其他平台上运行。

关于c - 读取另一个线程的寄存器或线程局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9992673/

相关文章:

linux - 如何从 web 发送参数或指令到 linux 机器并在 web 中显示结果?

caching - 写合并 : which cache line is avoided to be read before written?

c - “b++”的汇编

c - 如何将 CRC 函数从 C 转换为 Ruby?

C中的压缩程序

c++ - 如何修复 : undefined reference to "class::function"

html - 使用 sed 从 html 中提取 pdf

linux - 如何修复尝试调试简单的 nasm 汇编程序时出现 "sigsegv"的问题

仅当存在打印时代码才能正确执行 (C)

c - 802.11数据包的大小