windows 中 多线程编程 之 线程创建
线程创建有两种方法:
第一种方法,调用函数 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
);
参数解释:
lpThreadAttributes: 指向SECURITY_ATTRIBUTES型态的结构的指针。
dwStackSize:用于新线程的初始堆栈大小,默认值为0。在任何情况下,Windows根据需要动态延长堆栈的大小。
#include <iostream> #include "windows.h" using namespace std; DWORD WINAPI TestThread1(PVOID pParam) { while (1) { printf("PID %d TestThread1 running;\n", GetCurrentThreadId()); Sleep(1000); } return 0; } DWORD WINAPI TestThread2(PVOID pParam) { while (1) { printf("PID %d TestThread2 running;\n", GetCurrentThreadId()); Sleep(1000); } return 0; } int main() { HANDLE m_hProcesss1 = CreateThread(NULL, /* pointer to SECURITY_ATTRIBUTES */ 0, /* StackSize */ TestThread1, /* Thread Process */ 0, /* pointer to param */ 0, /* default zero */ 0); /* id */ HANDLE m_hProcesss2 = CreateThread(NULL, /* pointer to SECURITY_ATTRIBUTES */ 0, /* StackSize */ TestThread2, /* Thread Process */ 0, /* pointer to param */ 0, /* default zero */ 0); /* id */ WaitForSingleObject(m_hProcesss1, INFINITE); WaitForSingleObject(m_hProcesss2, INFINITE); CloseHandle(m_hProcesss1); CloseHandle(m_hProcesss2); return 0; }</span></strong>
结果
hThread = _beginthread (ThreadProc, uiStackSize, pParam) ;