例程1:传递整型参数
#include
#include
#include
DWORD WINAPI ThreadProFunc(LPVOID lpParam);
int main(int argc, char **argv)
{
HANDLE hThread;
DWORD dwThreadId;
int param = 20;
hThread = CreateThread( NULL, NULL, ThreadProFunc, ¶m , 0, &dwThreadId);
CloseHandle(hThread); //关闭线程句柄
system("pause");
return 0;
}
DWORD WINAPI ThreadProFunc(LPVOID lpParam)
{
printf("param = %d\n", *(int*)lpParam);
return 0;
}
运行结果:
param = 20
请按任意键继续. . .
例程2:传递字符串
#include
#include
#include
DWORD WINAPI ThreadProFunc(LPVOID lpParam);
int main(int argc, char **argv)
{
HANDLE hThread;
DWORD dwThreadId;
char param[] = "hello";
hThread = CreateThread( NULL, NULL, ThreadProFunc, param, 0, &dwThreadId);
CloseHandle(hThread); //关闭线程句柄
system("pause");
return 0;
}
DWORD WINAPI ThreadProFunc(LPVOID lpParam)
{
printf("param = %s\n", (char*)lpParam);
return 0;
}
运行结果
param = hello
请按任意键继续. . .
例程3:传递结构体参数
#include
#include
#include
typedef struct {
int x;
int y;
}Coord;
DWORD WINAPI ThreadProFunc(LPVOID lpParam);
int main(int argc, char **argv)
{
HANDLE hThread;
DWORD dwThreadId;
Coord param = {10, 20};
hThread = CreateThread( NULL, NULL, ThreadProFunc, ¶m , 0, &dwThreadId);
CloseHandle(hThread); //关闭线程句柄
system("pause");
return 0;
}
DWORD WINAPI ThreadProFunc(LPVOID lpParam)
{
printf("x = %d, y = %d\n", ((Coord*)lpParam)->x, (*(Coord*)lpParam)->y);
return 0;
}
运行结果
x = 10, y = 20
请按任意键继续. . .
例程4:传递对象(C++内置对象)
#include
#include
#include
#include
#include
using namespace std;
DWORD WINAPI ThreadProFunc(LPVOID lpParam);
int main(int argc, char **argv)
{
HANDLE hThread;
DWORD dwThreadId;
string str = "hello world";
//string *pStr = new string("nihao");
hThread = CreateThread( NULL, NULL, ThreadProFunc, &str, 0, &dwThreadId);
CloseHandle(hThread); //关闭线程句柄
system("pause");
return 0;
}
DWORD WINAPI ThreadProFunc(LPVOID lpParam)
{
cout << *(string*)lpParam << endl; // string 内置对象使用std::cout打印,printf不能直接打印
return 0;
}
运行结果
hello world
请按任意键继续. . .
例程4:传递对象(C++自定义对象)
#include
#include
#include
#include
#include
using namespace std;
class Coord {
public:
Coord(int x, int y)
{
m_iX = x;
m_iY = y;
}
~Coord(){};
void printInfo()
{
printf("coord(%d,%d)\n", m_iX, m_iY);
}
private:
int m_iX;
int m_iY;
};
DWORD WINAPI ThreadProFunc(LPVOID lpParam);
int main(int argc, char **argv)
{
HANDLE hThread;
DWORD dwThreadId;
Coord var(10,20);
hThread = CreateThread( NULL, NULL, ThreadProFunc, &var, 0, &dwThreadId);
CloseHandle(hThread); //关闭线程句柄
system("pause");
return 0;
}
DWORD WINAPI ThreadProFunc(LPVOID lpParam)
{
((Coord*)lpParam)->printInfo();
return 0;
}
运行结果
coord(10,20)
请按任意键继续. . .