【发布时间】:2016-03-25 06:40:45
【问题描述】:
我正在尝试使用 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;
}
【问题讨论】:
-
更具体地说,当我运行程序时,有时我得到的输出为 -
-
特别是当我运行这个程序时,有时我得到的输出只是 BBB BBB。我什至没有看到“我在”被打印一次,这表明我的方法没有被执行。 GetLastError 也总是返回 0
-
你需要等待线程结束。
标签: c++ windows multithreading visual-studio winapi