Linked Questions

Popular Questions

Finding Thread Id Of Called Function C++

Asked by At

In C++3 (VS 2008):

I want to find thread id of a called function when the function is called. Also I want to see when the function called; its name, file and line. My Example is here;

#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;
}

And here is output:

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

This works the way i want. I can put "cout <<..." line which contain GetCurrentThreadId() in every function, because there are only 2 functions here. But in my real product there are thousands function and it is impossible to put into every function to this "cout<<..."

I've been searching for two days about it and I've used a function whose name is _penter(). It seems useful, because it invoked before every called function. But I could not get from _penter(); thread id, function name, line and file info.

I want to ask two things:

  1. How can I do this without insert "cout<<..." to every function?
  2. If it is not possible how can I add "cout<<..." to my every function?

Any help would be highly appreciated...

Thank you...

Related Questions