【问题标题】:Finding Thread Id Of Called Function C++查找被调用函数 C++ 的线程 ID
【发布时间】:2016-12-19 13:11:29
【问题描述】:

在 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

我已经搜索了两天,我使用了一个名为 _penter() 的函数。它似乎很有用,因为它在每个被调用函数之前调用。但我无法从 _penter();线程 id、函数名、行和文件信息。

我想问两件事:

  1. 如何在不向每个函数中插入“cout
  2. 如果不可能,我如何将“cout

任何帮助将不胜感激...

谢谢...

【问题讨论】:

  • 我看到了三个直接选项: 1 使用一个您煞费苦心地放入每个函数的宏。 2. 使用装饰器模式来包装你的函数。 3. 编写您自己的预处理脚本,插入所需的代码。
  • Here's a tracing solution I made some time ago。您可以根据需要对其进行修改(例如,将线程 ID 添加到输出中)。
  • 您正在询问您的解决方案。但你真正想解决什么问题?
  • @AndyG 我会试试的。谢谢。
  • @Someprogrammerdude 谢谢,我在找。

标签: c++ multithreading visual-studio-2008


【解决方案1】:

在 C++11/14/17 中,它看起来像这样。

#include<thread>
void calledFunction(){

std::cout << \_\_func\_\_ << " called from thread:" << std::this_thread::get_id() << std::endl;

} 

【讨论】:

    猜你喜欢
    • 2011-08-27
    • 2019-07-13
    • 1970-01-01
    • 2015-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-21
    相关资源
    最近更新 更多