到目前为止,我只在 Linux 平台上使用过进程和线程。 现在我尝试转向Windows。我立即停止了一个非常简单的程序。 你能告诉我为什么如果我用 getch 删除该行,我的程序不会写任何东西吗? 我希望我的线程能够在不按下任何按钮的情况下完成。 预先感谢您
#include <windows.h>
#include <stdio.h>
DWORD WINAPI ThreadFunc()
{
printf("lets print something");
return 0;
}
VOID main( VOID )
{
DWORD dwThreadId;
HANDLE hThread;
hThread = CreateThread(
NULL, // default security attributes
0, // use default stack size
ThreadFunc, // thread function
NULL, // argument to thread function
0, // use default creation flags
&dwThreadId); // returns the thread identifier
// Check the return value for success.
if (hThread == NULL)
{
printf( "CreateThread failed (%d)\n", GetLastError() );
}
else
{
_getch();
CloseHandle( hThread );
}
}
最佳答案
如果您的机器相对空闲,操作系统很可能会向另一个核心发出线程创建请求的信号,因此允许“主”线程(由进程加载器创建的线程)快速运行。当您的新线程开始使用 printf 调用来调用操作系统时,主线程已经返回,该进程的所有线程的状态已设置为“不再运行”,并且终止请求已在队列中排队它的处理器间核心驱动程序。新线程立即被终止,并且现在冗余的终止请求被丢弃。
关于c - 简单的多线程,无需getch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21052802/