win32 CreateThread

CreateThread

网页:

https://msdn.microsoft.com/en-us/library/windows/desktop/ms682453(v=vs.85).aspx

在调用该函数的进程的虚拟地址空间 创建一个线程去执行
如果要创建一个线程,想要该线程运行在其他的进程的虚拟地址空间,使用函数CreateRemoteThread

HANDLE WINAPI CreateThread(
  _In_opt_  LPSECURITY_ATTRIBUTES  lpThreadAttributes,
  _In_      SIZE_T                 dwStackSize,
  _In_      LPTHREAD_START_ROUTINE lpStartAddress,
  _In_opt_  LPVOID                 lpParameter,
  _In_      DWORD                  dwCreationFlags,
  _Out_opt_ LPDWORD                lpThreadId
);

参数

lpThreadAttributes [in, optional]

一般设置NULL

指向SECURITY_ATTRIBUTES结构体的指针。
SECURITY_ATTRIBUTES结构体决定返回的句柄,是否可以被子进程继承。
如果lpThreadAttributes为NULL,该句柄不能被继承。

SECURITY_ATTRIBUTES结构体中的lpSecurityDescriptor 成员变量
为新建立的线程指定a security descriptor。
如果lpThreadAttributes 是NULL,线程得到一个默认的a default security descriptor。
The ACLs in the default security descriptor for a thread come from the primary token of the creator.

dwStackSize [in]

栈的初始大小,以字节为大小。
系统会将这个值,调整为最接近的page页的大小。
如果该参数为0,新的线程使用可执行的默认的大小。
进一步的信息,参考如下网址:Thread Stack Size.
https://msdn.microsoft.com/en-us/library/windows/desktop/ms686774(v=vs.85).aspx

lpStartAddress [in]

函数指针,指向预定义的线程执行函数。
这个指针表示线程函数的地址。

更多信息参考 :ThreadProc.

https://msdn.microsoft.com/en-us/library/windows/desktop/ms686736(v=vs.85).aspx

lpParameter [in, optional]

指向某个变量的指针,
该变量会被传给线程函数
A pointer to a variable to be passed to the thread.

dwCreationFlags [in]

The flags that control the creation of the thread.
控制线程创建的标志

Value Meaning
0 线程创建之后,立马执行
CREATE_SUSPENDED 0x00000004 被创建的线程,处于挂起状态,直到调用ResumeThread函数,线程才会执行
STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000 The dwStackSize parameter specifies the initial reserve size of the stack. If this flag is not specified, dwStackSize specifies the commit size.

lpThreadId [out, optional]

指针指向变量,该变量获取线程的ID。如果该参数为NULL,
线程ID不会返回。

返回值

如果函数成功,返回值为一个新的线程的句柄
如果函数失败,返回值为NULL。获得更多的error信息,调用GetLastError

注意:
如果lpStartAddress指向的是data,code,或者不可访问的地址区域,CreateThread都会成功。
当线程运行的时候,start address 不是有效的,将会产生一个exception,然后线程终止。
如果线程是因为无效的start address中止的,这个事情将会被线程所在的进程,看作一个 an error exit 。
Thread termination due to a invalid start address is handled as an error exit for the thread’s process. This behavior is similar to the asynchronous nature of CreateProcess, where the process is created even if it refers to invalid or missing dynamic-link libraries (DLLs).

Remarks

一个进程可以创建的线程的数量 有限的, 它和进程可用的虚拟内存有关。
默认的,每个线程有1M字节的栈空间。所以,你可以创建最多2048个线程。
如果你减小默认的栈空间的大小,可以创建更多的线程。
However, your application will have better performance if you create one thread per processor and build queues of requests for which the application maintains the context information. A thread would process all requests in a queue before processing requests in the next queue.
The new thread handle is created with the THREAD_ALL_ACCESS access right. If a security descriptor is not provided when the thread is created, a default security descriptor is constructed for the new thread using the primary token of the process that is creating the thread. When a caller attempts to access the thread with the OpenThread function, the effective token of the caller is evaluated against this security descriptor to grant or deny access.

新创建的thread ,使用GetCurrentThread 函数,对自己有完全的访问权限。

Windows Server 2003: The thread’s access rights to itself are computed by evaluating the primary token of the process in which the thread was created against the default security descriptor constructed for the thread. If the thread is created in a remote process, the primary token of the remote process is used. As a result, the newly created thread may have reduced access rights to itself when calling GetCurrentThread. Some access rights including THREAD_SET_THREAD_TOKEN and THREAD_GET_CONTEXT may not be present, leading to unexpected failures. For this reason, creating a thread while impersonating another user is not recommended.
如果线程是在runnable状态下创建的,也就是CREATE_SUSPENDED 标志没有使用,线程会在CreateThread函数返回之前,尤其是在调用者收到句柄和创建的线程的ID之后 运行。
线程从lpStartAddress参数指定的函数开始执行,如果这个函数返回,DWORD类型的返回值,用来终止线程。方法是隐式调用ExitThread函数。使用GetExitCodeThread函数来得到线程的返回值。
线程创建的时候,线程的优先级是THREAD_PRIORITY_NORMAL。使用GetThreadPriority 和SetThreadPriority函数,来获取和设置线程的优先级。
当线程停止,线程对象获得一个有信号的状态,满足任何正在等待这个线程对象的线程。
这个线程对象会一直存在,直到线程停止,线程的所有句柄通过CloseHandle关闭。

The ExitProcess, ExitThread, CreateThread, CreateRemoteThread functions, and a process that is starting (as the result of a call by CreateProcess) are serialized between each other within a process. Only one of these events can happen in an address space at a time. This means that the following restrictions hold:
During process startup and DLL initialization routines, new threads can be created, but they do not begin execution until DLL initialization is done for the process.
Only one thread in a process can be in a DLL initialization or detach routine at a time.
ExitProcess does not complete until there are no threads in their DLL initialization or detach routines.

A thread in an executable that calls the C run-time library (CRT) should use the _beginthreadex and _endthreadex functions for thread management rather than CreateThread and ExitThread; this requires the use of the multithreaded version of the CRT. If a thread created using CreateThread calls the CRT, the CRT may terminate the process in low-memory conditions.
Windows Phone 8.1: This function is supported for Windows Phone Store apps on Windows Phone 8.1 and later.
Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows Store apps on Windows 8.1, Windows Server 2012 R2, and later.

Examples

For an example, see Creating Threads.

https://msdn.microsoft.com/en-us/library/windows/desktop/ms682516(v=vs.85).aspx

CreateThread函数为一个进程创建一个线程。
创建的线程,必须要指定要执行的代码的起始地址。一般的起始地址是函数的名字。
这个函数有一个参数和一个DWORD返回值。
一个进程可以有多个线程同时执行相同的函数。
下面是一个简单的例子,用来演示怎么创建一个新的线程来执行本地预定义的函数,MyThreadFunction。
调用的线程使用WaitForMultipleObjects函数来等待直到所有的worker线程停止。
调用的线程在等待的时候,阻塞。
如果要继续处理,调用的线程需要使用WaitForSingleObject 来等待每个worker线程来给它的等待对象发信号。
如果一个worker线程没有停止,但是你想要close它的句柄。
这样操作不会停止这个worker线程。
但是,记下来后面的函数调用使用这个句柄,都无效了。

具体代码如下:

#include <windows.h>
#include <tchar.h>
#include <strsafe.h>

#define MAX_THREADS 3
#define BUF_SIZE 255

DWORD WINAPI MyThreadFunction( LPVOID lpParam );
void ErrorHandler(LPTSTR lpszFunction);

// Sample custom data structure for threads to use.
// This is passed by void pointer so it can be any data type
// that can be passed using a single void pointer (LPVOID).
typedef struct MyData {
    int val1;
    int val2;
} MYDATA, *PMYDATA;


int _tmain()
{
    PMYDATA pDataArray[MAX_THREADS];
    DWORD   dwThreadIdArray[MAX_THREADS];
    HANDLE  hThreadArray[MAX_THREADS]; 

    // Create MAX_THREADS worker threads.

    for( int i=0; i<MAX_THREADS; i++ )
    {
        // Allocate memory for thread data.

        pDataArray[i] = (PMYDATA) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
                sizeof(MYDATA));

        if( pDataArray[i] == NULL )
        {
           // If the array allocation fails, the system is out of memory
           // so there is no point in trying to print an error message.
           // Just terminate execution.
            ExitProcess(2);
        }

        // Generate unique data for each thread to work with.

        pDataArray[i]->val1 = i;
        pDataArray[i]->val2 = i+100;

        // Create the thread to begin execution on its own.

        hThreadArray[i] = CreateThread( 
            NULL,                   // default security attributes
            0,                      // use default stack size  
            MyThreadFunction,       // thread function name
            pDataArray[i],          // argument to thread function 
            0,                      // use default creation flags 
            &dwThreadIdArray[i]);   // returns the thread identifier 


        // Check the return value for success.
        // If CreateThread fails, terminate execution. 
        // This will automatically clean up threads and memory. 

        if (hThreadArray[i] == NULL) 
        {
           ErrorHandler(TEXT("CreateThread"));
           ExitProcess(3);
        }
    } // End of main thread creation loop.

    // Wait until all threads have terminated.

    WaitForMultipleObjects(MAX_THREADS, hThreadArray, TRUE, INFINITE);

    // Close all thread handles and free memory allocations.

    for(int i=0; i<MAX_THREADS; i++)
    {
        CloseHandle(hThreadArray[i]);
        if(pDataArray[i] != NULL)
        {
            HeapFree(GetProcessHeap(), 0, pDataArray[i]);
            pDataArray[i] = NULL;    // Ensure address is not reused.
        }
    }

    return 0;
}


DWORD WINAPI MyThreadFunction( LPVOID lpParam ) 
{ 
    HANDLE hStdout;
    PMYDATA pDataArray;

    TCHAR msgBuf[BUF_SIZE];
    size_t cchStringSize;
    DWORD dwChars;

    // Make sure there is a console to receive output results. 

    hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
    if( hStdout == INVALID_HANDLE_VALUE )
        return 1;

    // Cast the parameter to the correct data type.
    // The pointer is known to be valid because 
    // it was checked for NULL before the thread was created.

    pDataArray = (PMYDATA)lpParam;

    // Print the parameter values using thread-safe functions.

    StringCchPrintf(msgBuf, BUF_SIZE, TEXT("Parameters = %d, %d\n"), 
        pDataArray->val1, pDataArray->val2); 
    StringCchLength(msgBuf, BUF_SIZE, &cchStringSize);
    WriteConsole(hStdout, msgBuf, (DWORD)cchStringSize, &dwChars, NULL);

    return 0; 
} 



void ErrorHandler(LPTSTR lpszFunction) 
{ 
    // Retrieve the system error message for the last-error code.

    LPVOID lpMsgBuf;
    LPVOID lpDisplayBuf;
    DWORD dw = GetLastError(); 

    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | 
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        dw,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR) &lpMsgBuf,
        0, NULL );

    // Display the error message.

    lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, 
        (lstrlen((LPCTSTR) lpMsgBuf) + lstrlen((LPCTSTR) lpszFunction) + 40) * sizeof(TCHAR)); 
    StringCchPrintf((LPTSTR)lpDisplayBuf, 
        LocalSize(lpDisplayBuf) / sizeof(TCHAR),
        TEXT("%s failed with error %d: %s"), 
        lpszFunction, dw, lpMsgBuf); 
    MessageBox(NULL, (LPCTSTR) lpDisplayBuf, TEXT("Error"), MB_OK); 

    // Free error-handling buffer allocations.

    LocalFree(lpMsgBuf);
    LocalFree(lpDisplayBuf);
}

The MyThreadFunction function avoids the use of the C run-time library (CRT), as many of its functions are not thread-safe, particularly if you are not using the multithreaded CRT. If you would like to use the CRT in a ThreadProc function, use the _beginthreadex function instead.
It is risky to pass the address of a local variable if the creating thread exits before the new thread, because the pointer becomes invalid. Instead, either pass a pointer to dynamically allocated memory or make the creating thread wait for the new thread to terminate. Data can also be passed from the creating thread to the new thread using global variables. With global variables, it is usually necessary to synchronize access by multiple threads. For more information about synchronization, see Synchronizing Execution of Multiple Threads.
The creating thread can use the arguments to CreateThread to specify the following:
The security attributes for the handle to the new thread. These security attributes include an inheritance flag that determines whether the handle can be inherited by child processes. The security attributes also include a security descriptor, which the system uses to perform access checks on all subsequent uses of the thread’s handle before access is granted.
The initial stack size of the new thread. The thread’s stack is allocated automatically in the memory space of the process; the system increases the stack as needed and frees it when the thread terminates. For more information, see Thread Stack Size.
A creation flag that enables you to create the thread in a suspended state. When suspended, the thread does not run until the ResumeThread function is called.
You can also create a thread by calling the CreateRemoteThread function. This function is used by debugger processes to create a thread that runs in the address space of the process being debugged.

猜你喜欢

转载自blog.csdn.net/wowocpp/article/details/80584225