2015-09-27 61 views
1
#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++中正常工作?

大家好。最近我開始在我的大學學習操作系統課程。 我有機會了解線程和多線程。我的教授給了我一個關於如何在C++中啓動多線程程序的示例代碼幻燈片。

所以我決定使用他的代碼作爲基礎,並決定稍微調整一下,這樣我就可以更好地理解它。

請忽略我所做的所有評論(大多數評論不適用於這個程序,這些評論基本上在幻燈片中,我只是把它留在那裏作爲參考)。

所以我已經調整過產生「嘿!」 「x」次取決於用戶輸入「x」的數字。正如你所看到的,我將它打印在printNumber函數內部(關於名稱很抱歉,因爲我的主要任務是打印素數,所以請原諒我)。

所以程序運行良好,準確地產生「嘿!」多次。

但這是問題。由於我的教授希望我使用多線程,我如何使用C++驗證自己是否正在使用多線程運行程序?

這個程序好像在打印「你好!」 (就像在單個線程下一樣),並且我無法判斷是否已將多線程應用於該程序。請記住,我並不那麼熟悉這些語法,這是我第一次在C++中使用WINAPI以及第一次執行線程編程。

非常感謝。

+1

在'printNumber'裏面打印'GetCurrentThreadId',每個線程都有一個單獨的id。 – user657267

+0

非常感謝。我在main和printNumber函數中都包含了它們,它們碰巧有不同的Id,我相信這意味着它們在不同的線程上運行。 –

回答

1

GetCurrentThreadId將返回當前線程的唯一標識符,如果您在線程函數中輸入此值並且main您應該發現它返回不同的值。

相關問題