Naren
Naren

Reputation: 31

How to identify function called from thread or process in msvc

I have program like below, function Foo is called by threds and main process. Now how to identify funtion Foo is called by thread or main process.

#include <Windows.h>
#include <stdio.h>
DWORD WINAPI Foo(LPVOID lPtr);
int main()
{
    DWORD dwExitCode;
    DWORD dwThreadID;
    HANDLE hT[10];
    int i;
    for( i = 0; i<5; i++)
    hT[i] = CreateThread(
        NULL,
        0,
        Foo,
        0,
        0,
        &dwThreadID
        );
        fflush(stdout); 
    Foo(0);
    return 0;
}

DWORD WINAPI Foo(LPVOID lPtr){
  printf("\ninside the Function");
  return 0;
}

Upvotes: 0

Views: 64

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 597166

Call GetCurrentThreadId() in main(), and again in Foo(), and see if the two values match or not, eg:

#include <Windows.h>
#include <stdio.h>

DWORD WINAPI Foo(LPVOID lPtr);
DWORD dwMainThreadId;

int main() {
    DWORD dwExitCode;
    DWORD dwThreadID;
    HANDLE hT[10];
    int i;

    dwMainThreadId = GetCurrentThreadId();

    for( i = 0; i<5; i++)
        hT[i] = CreateThread(
            NULL,
            0,
            Foo,
            0,
            0,
            &dwThreadID
        );
    fflush(stdout);
    Foo(0);
    return 0;
}

DWORD WINAPI Foo(LPVOID lPtr){
    DWORD dwThisThreadId = GetCurrentThreadId();
    printf(
        "\ninside the Function in thread %u (%s)",
        dwThisThreadId,
        (dwThisThreadId == dwMainThreadId) ? "main" : "worker"
    );
    return 0;
}

Upvotes: 2

Related Questions