2

私は VC2010 を使用しており、「__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;
}

しかし、コンソールには何も出力されません。コードの何が問題になっていますか?

4

1 に答える 1

5

メインルーチンはすぐに終了し、プロセスの一部であるすべてのスレッドを含むプロセス全体がすぐにシャットダウンします。あなたの新しいスレッドが実行を開始する機会さえあったとは思えません。

これを処理する一般的な方法は、WaitForSingleObjectを使用して、スレッドが完了するまでブロックすることです。

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;
}
于 2012-06-16T16:12:30.247 に答える