A multi-threaded instance
#include"stdafx.h"#include<windows.h>DWORD __stdcall Func (lpvoid pm) {printf_s ("This is a thread, id =%d \ n", GetCurrentThreadID ()); return 0;}intMain () {HANDLE h= CreateThread (NULL,0, Func, NULL,0, NULL); WaitForSingleObject (H, INFINITE); System ("Pause"); return 0;}
The operation results are as follows
CreateThread function prototype
HANDLE WINAPI CreateThread (
lpsecurity_attributes lpthreadattributes,//security properties for thread kernel objects, NULL for default settings
size_t dwstacksize,//Line stacks space size. 0 means using the default size (1MB)
Lpthread_start_routine lpstartaddress,//thread function address
lpvoid lpparameter,//parameters of the thread function
DWORD dwcreationflags,///extra flag to control thread creation, 0 means immediate execution
Lpdword lpthreadid//thread ID number, NULL indicates no need to return
);
function returns the handle of the thread
WaitForSingleObject function prototype
DWORD WINAPI WaitForSingleObject (
HANDLE hhandle,//kernel object handle
DWORD dwmilliseconds// maximum wait time, in milliseconds, such as 1000 for 1 seconds, incoming 0 returns immediately, incoming infinite means infinite wait.
);
WaitForSingleObject can wait for a kernel object to be triggered, because the thread is not triggered when it is running , the thread ends and the thread object is in a triggered state, so you can use
WaitForSingleObject (H, INFINITE);
Wait for a thread to finish executing,
function returns,
Wait_object_0 object is triggered within the wait time
Wait_timeout object has not been triggered within the wait time
Wait_failed parameter Error
You can use the following code to determine whether a thread is running state
BOOL isruning () { // Run Detect ifreturnfalse; if (WaitForSingleObject (M_hthreadhandle,0returnfalse;//Pass 0 means return immediately, wait_ Timeout means that the object is not triggered, that is, the thread is not stopped
returntrue
}
C + + Multithreading 1