c++ - 查找被调用函数的线程 ID C++

标签 c++ multithreading visual-studio-2008

在 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、函数名称、行和文件信息。

我想问两件事:

  1. 如何在不向每个函数插入“cout<<...”的情况下执行此操作?
  2. 如果不可能,我该如何将“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/

相关文章:

c++ - 如何加快程序的启动速度

c++ - 哈希函数中的大括号是什么?

C#,我可以在不尝试获取锁的情况下检查它吗?

python - 执行python脚本时,脚本在线程上阻塞,但不在交互模式下

c++ - 如何添加与 lib 文件关联的 .pdb 文件?

visual-studio-2008 - 如何强制 Visual Studio 2008 使用正确的语言环境保存 vcproj 文件?

c++ - 有时VS2008需要很长时间才能编译

c++ - 使用 boost::algorithm::split_regex 拆分字符串

c++ - 非托管类的成员不能有 ref 类类型或接口(interface)类类型

C:将使用 tmpfile() 函数创建的临时文件与多线程合并