Windows系统——线程创建
实现代码
#include<bits/stdc++.h>
#include<windows.h>
struct Parameter{
int low;
int high;
Parameter(int l, int h) : low(l), high(h) {}
};
DWORD WINAPI Print(LPVOID Param)
{
Parameter* p = (Parameter*) Param;
for(int i = p->low; i < p->high; i++) {
printf("%d ", i);
}
printf("\n");
return 0;
}
int main(int argc, char const *argv[])
{
Parameter Param(1,10);
DWORD dwThreadID;
static HANDLE hThread;
hThread = CreateThread(
NULL,
0,
Print,
&Param,
0,
&dwThreadID
);
if(hThread != NULL) {
printf("Subthread is running!\n");
WaitForSingleObject(hThread, INFINITE);
printf("Main thread is runing!\n");
}
ExitThread(0);
return 0;
}
输出结果
Subthread is running!
1 2 3 4 5 6 7 8 9
Main thread is runing!
CreateThread()
- 返回值
返回创建线程句柄 - 函数声明
HANDLE WINAPI CreateThread(
In_opt LPSECURITY_ATTRIBUTES lpThreadAttributes,
In SIZE_T dwStackSize,
In LPTHREAD_START_ROUTINE lpStartAddress,
In_opt __drv_aliasesMem LPVOID lpParameter,
In DWORD dwCreationFlags,
Out_opt LPDWORD lpThreadId
);
- 参数LPSECURITY_ATTRIBUTES设置安全属性,NULL为默认安全性,不可以被子线程继承
- 参数dwStackSize设置初始栈的大小,以字节为单位,如果为0,那么默认将使用与调用该函数的线程相同的栈空间大小
- 参数lpStartAddress,函数指针,指向线程执行函数
- 参数lpParameter,向线程函数传递参数,无需传参数则为NULL
- 参数dwCreationFlags,线程创建标志,设置挂起或执行
- 参数lpThreadId,返回新建线程ID
最后
- 由于博主水平有限,不免有疏漏之处,欢迎读者随时批评指正,以免造成不必要的误解!