How to use "__beginthreadex" correctly?

I am using VC2010, and write following code to test "__beginthreadex"

#include <process.h>
#include <iostream>

unsigned int __stdcall threadproc(void* lparam)
{
    std::cout << "my thread" << std::endl;
    return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
    unsigned  uiThread1ID = 0;
    uintptr_t th = _beginthreadex(NULL, 0, threadproc, NULL, 0, &uiThread1ID);

    return 0;
}

But nothing is printed to the console. What's wrong with my code?

Answers


Your main routine exits right away, causing the entire process to shutdown immediately, including all threads that are a part of the process. Its doubtful your new thread even had a chance to begin execution.

The typical way to handle this is to use WaitForSingleObject and block until the thread is complete.

int _tmain(int argc, _TCHAR* argv[])
{
    unsigned  uiThread1ID = 0;
    uintptr_t th = _beginthreadex(NULL, 0, threadproc, NULL, 0, &uiThread1ID);

    // block until threadproc done
    WaitForSingleObject(th, INFINITE/*optional timeout, in ms*/);

    return 0;
}

Need Your Help

WPF C# - XML Edit Binding in Treeview

c# wpf xml binding editing

I think this is a very basic question, but I can't find answer to it.

On Eclipse Mars, I can't see 1.8 in the compiler compliance level menu

java-8 eclipse-mars

I'm using Eclipse Mars and I can't see 1.8 in the compiler compliance level menu.