wyf*_*izj 2 c++ multithreading visual-c++
我正在使用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;
}
Run Code Online (Sandbox Code Playgroud)
但没有任何东西打印到控制台.我的代码出了什么问题?
您的主例程立即退出,导致整个过程立即关闭,包括作为该过程一部分的所有线程.令人怀疑的是你的新线程甚至有机会开始执行.
处理此问题的典型方法是使用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;
}
Run Code Online (Sandbox Code Playgroud)