#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#define MAX_THREADS 1
#include <windows.h>
#include <iostream>
using namespace std;
DWORD WINAPI printNumbe(LPVOID);
// We need an array of Handles to threads
HANDLE hThreads[MAX_THREADS];
//...an array of thread id's
DWORD id[MAX_THREADS];
//And a waiter
DWORD waiter;
DWORD WINAPI printNumber(LPVOID n)
{
int num = (int)n;
for (int i = 0; i <= num; i++)
{
cout << "Hey there!" << endl;
}
return (DWORD)n;
}
//get ready, because here's where all the REAL magic happens
int main(int argc, char* argv[])
{
int number;
cout << "Please enter a number:" << endl;
cin >> number;
//here is where we call the CreateThread Win32 API Function that actually
//creates and begins execution of thread
//please read your help files for what each parameter does on
//your Operating system.
//Here's some basics:
//Parameter 0: Lookup, 1: Stack Size, 2: The function to run with this thread, 3: Any parameter that you want to pass to thread
//function, 4: Lookup , 5: Once thread is created, an id is put in this variable passed in
hThreads[0] = CreateThread(NULL, 0, printNumber, (LPVOID)number, NULL, &id[0]);
//now that all three threads are created and running, we need to stop the primary thread
// which is this program itself - remember that once "main" returns, our program exits
//so that our threads have time to finish. To do this, we do what is called "Blocking"
//we're going to make main just stop and wait until all three threads are done
//this is done easily with the next line of code. please read the help file about the specific API call
//"WaitForMultipleObjects"
waiter = WaitForMultipleObjects(MAX_THREADS, hThreads, TRUE, INFINITE);
//after all three threads have finished their task, "main" resumes and we're now ready
//to close the handles of the threads. This is just a bit of clean up work.
//Use the CloseHandle (API) function to do this.
for (int i = 0; i < MAX_THREADS; i++)
{
CloseHandle(hThreads[i]);
}
system("PAUSE");
return 0;
}
大家好。最近我开始在我的大学学习操作系统课程。 我有机会学习线程和多线程。我的教授给了我一个关于如何在C ++中启动多线程程序的示例代码的功能点幻灯片。
所以我决定使用他的代码作为基础,并决定稍微调整一下,以便我能更好地理解它。
请忽略我所做的所有评论(大多数评论不适用于此计划,这些评论基本上都在幻灯片中,我只是将其留在那里作为参考)。
所以我已经调整生产&#34;嘿那里!&#34; &#34; X&#34;时间取决于用户输入的数字&#34; x&#34;。正如你所看到的,我把它打印在printNumber函数内部(抱歉这个名字,因为我的主要任务是打印素数,所以请原谅我)。
所以程序运行正常并准确生成&#34;嘿那里!&#34;多次。
但问题是这里。由于我的教授要我使用多线程,我如何在C ++中验证自己运行多线程的程序?
这个程序好像在打印&#34;嘿那里!&#34;连续(就像在单个线程下一样)并且我无法判断是否已将多线程应用于程序。
请记住,我不熟悉这些语法,这是我第一次在C ++中使用WINAPI以及第一次使用线程编程。
非常感谢你。