c++ - WINAPI CreateThread 并不总是运行线程

标签 c++ windows multithreading visual-studio winapi

我正在尝试使用 Windows CreateThread API 创建和执行线程。我看到运行该程序会产生不确定的行为。我从程序的输出中看到,线程方法“my”有时会被执行,有时不会。这可能是什么原因?该程序非常简单,如下所示。还有应该用什么初始化 dwThreadID。它应该是 0 还是任何整数值? PS:在Visual Studio中编译。

#include "stdafx.h"
#include <iostream>  
#include <windows.h>  
using namespace std;

// DWORD WINAPI   
DWORD  WINAPI my (LPVOID lpParam ) {  
    for (int i = 0; i < 5;i++){  
        cout << "I am ";  
    } 
    return 0; 
} 

int main()  
{
    DWORD dwThreadID = 0;   
    DWORD dwThrdParam = 0;  
    HANDLE h = NULL; 
    h = CreateThread(
            NULL,              // default security
            0,                 // default stack size
            my,        // name of the thread function
            0,              // no thread parameters
            0,                 // default startup flags
            &dwThreadID); 
     if (h == NULL){  
         cout <<"It is null";
     }      
    cout << " BBBB" << endl ;  
    CloseHandle(h); 
    cout << "BBBB "; 
    return 0;  
}

最佳答案

I am seeing from the output of the program that sometimes the thread method "my" gets executed and sometimes not. What might be the reason for this?

可能您的主线程甚至在您的第二个线程执行之前就退出了。在调用 CreateThread 后放置断点。

或者更干净的等待,只需使用 WaitForSingleObject 等待第二个线程. 这有效地使您的主线程等待“我的”线程完成。

如果 CreateThread 由于某种原因失败,您可以调用 GetLastErrorCreateThread 之后,它会给你最终的答案。

Also what should dwThreadID be initialized with.

快速查看 MSDN产量如下:

A pointer to a variable that receives the thread identifier.

关于c++ - WINAPI CreateThread 并不总是运行线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36215265/

相关文章:

c++ - QML 中的两种方式绑定(bind) C++ 模型

windows - Docker + Windows + 普罗米修斯 : How/Where to supply the configuration files

python - 从 re.sub 调用函数

java - 调用并使用 .interrupt() 方法?

c# - 被遗弃的互斥异常

python - 杀死多线程SocketServer

c++ - QT QSyntaxHighlighter - setCurrentBlockState 的作用是什么?

c++ - 无法调整缓冲区以适应数据

c++ - 传递一些东西作为这个参数丢弃限定符

无法使用 MinGW 在 Windows 上编译 GTK+ 程序