简体   繁体   English

如何在jvmti中唯一标识线程

[英]How to uniquely identify thread in jvmti

i'm working on JVMTI agent and I want to identify same thread on method enter and exit. 我正在研究JVMTI代理,我想在方法输入和退出时识别相同的线程。 I'm able to obtain thread name, but that's not sufficient. 我能够获得线程名称,但这还不够。

Imagine you have a method like this: 想象一下,你有一个像这样的方法:

public class Main {
    public static void myMethod() {
        System.out.println("doing something as " + Thread.currentThread().getName());
        Thread.currentThread().setName("SomethingDifferent");
        System.out.println("doing something as same thread " + Thread.currentThread().getName());
    }
}

So entering this method will have one name and exiting this thread have different name. 因此,输入此方法将有一个名称,并退出此线程具有不同的名称。

When using JVMTI like this: 当像这样使用JVMTI时:

static void JNICALL callback_on_method_entry(jvmtiEnv *jvmti, JNIEnv* env,
    jthread thread, jmethodID method)
{
    ...
    (*jvmti)->GetThreadInfo(jvmti, thread, &info);
    ...
}

static void JNICALL callback_on_method_exit(jvmtiEnv *jvmti, JNIEnv *env, jthread thread, jmethodID method, jboolean was_popped_by_exception, jvalue return_value)
{
    ...
    (*jvmti)->GetThreadInfo(jvmti, thread, &info);
    ...
}

Each info will report different thread name and I want to have the same identifier for them. 每个info都会报告不同的线程名称,我希望它们具有相同的标识符。

How can I get the same identifier for the thread ? 如何获得线程的相同标识符?

One solution can be to get field value of referenced Thread ( tid ). 一种解决方案可以是获取引用的Threadtid )的字段值。 How to do that ? 怎么做 ? I can iterat through the heap but I cannot get the field name. 我可以通过堆迭代但​​我无法得到字段名称。

One solution, as you pointed out, would be to use GetFieldName. 正如您所指出的,一种解决方案是使用GetFieldName。 That requires you to lookup the jfieldid, which can be really annoying. 这需要你查找jfieldid,这可能真的很烦人。

The way i've seen others do it, is to simply assign their own ID's and stash it in the thread local storage. 我看到其他人这样做的方法是简单地分配他们自己的ID并将其存储在线程本地存储中。 See JavaThreadLayer.cpp from UofO's TAU project, specifically the JavaThreadLayer::GetThreadId() function. 请参阅UofO的TAU项目中的JavaThreadLayer::GetThreadId() ,特别是JavaThreadLayer::GetThreadId()函数。

I finally found another simple soulution: 我终于找到了另一种简单的方法:

Because the entry/exit callbacks are running in the same thread, it's possible to use pthread_self() and cast it eg to unsigned int . 因为进入/退出回调在同一个线程中运行,所以可以使用pthread_self()并将其转换为unsigned int It's not the same tid as you can find in java, but you will get the unique number for thread although the name changes. 这与你在java中找到的tid不一样,但是你会得到线程的唯一编号,尽管名称会改变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM