1
我正在嘗試編寫一小段代碼,使得使用CreateThread()稍微更乾淨一些。我不能說我真的打算使用它,但我認爲這對於像我這樣的新程序員來說是一個有趣的小項目。以下是我迄今爲止:將函數作爲參數傳遞以簡化線程創建
#include <iostream>
#include <windows.h>
using namespace std;
void _noarg_thread_create(void(*f)())
{
cout << "Thread created...\n" << endl;
Sleep(10);
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)f, NULL, 0, NULL);
}
template <typename T>
void _arg_thread_create(void(*f)(T), T* parameter)
{
cout << "Thread created...\n" << endl;
Sleep(10);
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)*f, parameter, 0, NULL);
}
void printnums(int x)
{
for(int i = x; i < 100; i++)
{
cout << i << endl;
}
}
void printnumsnoarg()
{
for(int i = 0; i < 100; i++)
{
cout << i << endl;
}
}
int main()
{
cin.get();
_noarg_thread_create(&printnumsnoarg);
cin.get();
int x = 14;
_arg_thread_create(&printnums, &x);
cin.get();
}
基本上我有兩個功能,將調用兩個不同的預設,CreateThread的:一個當需要在線程參數,和一個當需要在沒有參數線。我可以用g ++編譯器(cygwin)編譯,並且運行時沒有任何錯誤。第一個線程得到正確創建,並按預期輸出數字0-99。但是,第二個線程不會打印出任何數字(使用此代碼,它應該打印14-99)。我的輸出如下所示:
<start of output>
$ ./a.exe
Thread created...
0
1
2
3
.
.
.
97
98
99
Thread Created...
<end of output>
任何想法爲什麼第二個線程不能正常工作?
您傳遞給'CreateThread'的函數應該有'DWORD WINAPI(LPVOID)'簽名。你似乎忽略了這一點。 – chris 2013-03-05 21:17:19
也許是因爲'_noarg_thread_create'首次調用'cin.get();'之後?第二件事:C++現在有一個很好的[std :: thread](http://en.cppreference.com/w/cpp/thread/thread)。我認爲,使用它會更好 – borisbn 2013-03-05 21:22:46