c - 简单的多线程,无需getch

标签 c multithreading

到目前为止,我只在 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/

相关文章:

c - &p 和 p 有什么区别

c++ - Libpcap - 接收与发送数据包

c - 为什么我的管道在我的多线程客户端-服务器程序中不起作用?

multithreading - 在实践中,信号量与自旋锁的成本有多高?

php - 用于开发 PHP 扩展的调试器

c - 在 C 中访问二维数组的元素

java - Android TCP/IP 和 GUI 到其他线程的通信 - Tic Tac Toe 多人游戏

c - Linux 内核 - 如何停止等待信号量的 kthread?

ios - 多线程核心数据 : 'Main' context thread

c# - C# 中的多线程 NamePipeServer