【问题标题】:Simple multithreading without getch没有 getch 的简单多线程
【发布时间】:2014-01-29 22:14:58
【问题描述】:

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

【问题讨论】:

  • 如果你在 VS 中运行程序,控制台窗口可能会立即消失。通过提供 _getch(),控制台窗口将等到您点击 _getche()。
  • 是的,我的第一个想法。然后我在终端用 gcc 试了一下。没用。
  • 那么您的主线程可能在创建另一个线程之前已经关闭。因此,您无法看到该消息。

标签: c multithreading


【解决方案1】:

如果您的机器相对空闲,操作系统很可能会向另一个内核发送线程创建请求,因此允许“主”线程(由进程加载程序创建的线程)快速运行。当您的新线程开始使用 printf 调用调用操作系统时,主线程已经返回,该进程的所有线程的状态已设置为“不再运行”并且终止请求排队等待它它的处理器间核心驱动程序。新线程在那里被终止,现在冗余的终止请求被丢弃。

【讨论】:

  • 感谢您的回答。但是我应该如何解决这个问题?我尝试添加usleep,结果相同。编辑:然后我尝试了睡眠,它有效。
  • @user31 很简单,等待线程在存在之前终止。请参阅 WaitForSingleObject,尽管无论如何您都不应该使用 CreateThread - 请参阅 _beginthreadex 和 CreateThread 文档了解原因。
猜你喜欢
  • 2018-10-27
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多