先看下面一个例子
//Tread.cpp
#include <iostream>
#include <cstdlib>
using namespace std;
#include <Windows.h>
#include <process.h>
unsigned _stdcall ThreadProc1(void* param);
unsigned _stdcall ThreadProc2(void* param);
int main()
{
HANDLE handle1 = (HANDLE)_beginthreadex(NULL, 0, ThreadProc1, NULL, NULL, NULL);
HANDLE handle2 = (HANDLE)_beginthreadex(NULL, 0, ThreadProc2, NULL, NULL, NULL);
if ((handle1 == NULL) | (handle2 == NULL))
{
cout<<"create thread failed"<<endl;
system("pause");
return 0;
}
WaitForSingleObject(handle1, INFINITE);
cout<<"Thread1 is over"<<endl;
WaitForSingleObject(handle2, INFINITE);
cout<<"Thread2 is over"<<endl;
CloseHandle(handle1);
CloseHandle(handle2);
system("pause");
return 0;
}
unsigned _stdcall ThreadProc1(void* param)
{
for(int i=0; i<3; i++)
{
cout<<"_beginthreadex create thread___1"<<endl;
Beep(1000,500);
}
return 0;
}
unsigned _stdcall ThreadProc2(void* param)
{
for(int i=0; i<6; i++)
{
cout<<"_beginthreadex create thread___2"<<endl;
Beep(1000,500);
}
return 0;
}
_beginthreadx 参数依次为
安全属性,默认为NULL
线程堆栈大小,默认为0,表示同父线程
线程函数名,线程任务
线程参数,此处为NULL,若有参数建议结构体传递
线程标志,0(NULL)或者CREATE_SUSPEND 立即执行或者创建后挂起
线程ID,不用的话可以为NULL
下面是另一个传递参数的线程例子。
对比可以发现一些现成的书写特点。
Thread.cpp #include <Windows.h> #include <process.h> #include <iostream> #include <cstdlib> using namespace std; struct ThreadInfo { int param; }; unsigned _stdcall ThreadProc(void* param) { ThreadInfo * Info = (ThreadInfo*)param; int count = Info->param; for(int i=0; i<count; i++) { cout<<"_beginthreadex create thread"<<endl; cout<<"The Thread ID is"<<GetCurrentThreadId()<<endl; Beep(1000,500); } return 0; } int main() { HANDLE handle; DWORD ThreadID; ThreadInfo Info; Info.param = 5; handle = (HANDLE)_beginthreadex(NULL, 0, &ThreadProc, &Info, 0, (unsigned *)&ThreadID); if (handle == NULL) { cout<<"create thread failed"<<endl; system("pause"); return 0; } WaitForSingleObject(handle, INFINITE); cout<<"Thread is over"<<endl; CloseHandle(handle); system("pause"); return 0; }
额,这个还是没用到线程 ID。但是得到了。