在 C++3(VS 2008)中:
我想在调用函数时找到被调用函数的线程 ID。我还想看看函数何时调用;它的名称、文件和行。我的例子在这里;
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <process.h>
#include <windows.h>
void test(void *param)
{
cout << "In thread function" << endl;
cout << "(" << __FUNCTION__ << ") function in " << __FILE__ << " (line: " << __LINE__ << ") was called by thread id: " << GetCurrentThreadId() << endl;
Sleep(1000); // sleep for 1 second
cout << "Thread function ends" << endl;
threadFinished = true;
_endthread();
}
int main()
{
cout << "Starting thread" << endl;
cout << "(" << __FUNCTION__ << ") function in " << __FILE__ << "(line: " << __LINE__ << ") was called by thread id: " << GetCurrentThreadId() << endl;
_beginthread(test,0,NULL);
while(!threadFinished)
{
Sleep(10);
}
cout << "Main ends" << endl;
getchar();
return 0;
}
这是输出:
Starting thread
(main) function in .\CatchThread.cpp (line: 36) was called by thread id: 8200
In thread function
(test) function in .\CatchThread.cpp (line: 26) was called by thread id: 8860
Thread function ends
Main ends
这按我想要的方式工作。我可以在每个函数中放入包含 GetCurrentThreadId() 的“cout <<...”行,因为这里只有 2 个函数。但是在我的实际产品中有成千上万的功能,不可能将每个功能都放入这个“cout<<...”
我已经为此搜索了两天,并且使用了一个名为 _penter() 的函数。它看起来很有用,因为它在每个被调用的函数之前调用。但是我无法从 _penter();线程 ID、函数名称、行和文件信息。
我想问两件事:
- 如何在不向每个函数插入“cout<<...”的情况下执行此操作?
- 如果不可能,我该如何将“cout<<...”添加到我的每个函数中?
任何帮助将不胜感激......
谢谢...
最佳答案
在 C++11/14/17 中它看起来像这样。
#include<thread>
void calledFunction(){
std::cout << \_\_func\_\_ << " called from thread:" << std::this_thread::get_id() << std::endl;
}
关于c++ - 查找被调用函数的线程 ID C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41223364/