Windows核心編程:第6章 線程基礎

Github

https://github.com/gongluck/Windows-Core-Program.gitc++

//第6章 線程基礎.cpp: 定義應用程序的入口點。
//

#include "stdafx.h"
#include "第6章 線程基礎.h"
#include <process.h>

//線程函數
DWORD WINAPI ThreadProc(PVOID param)
{
    return 0;
}
unsigned __stdcall ThreadProc2(void* param)
{
    return 0;
}

int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
                     _In_opt_ HINSTANCE hPrevInstance,
                     _In_ LPWSTR    lpCmdLine,
                     _In_ int       nCmdShow)
{
    //建立Windows線程
    HANDLE hthread = CreateThread(nullptr, 0, ThreadProc, nullptr, CREATE_SUSPENDED, nullptr);
    ResumeThread(hthread);
    system("pause");
    BOOL bret = TerminateThread(hthread, 0);//終止線程(異步),可能會致使資源沒有釋放(例如沒有調用線程裏類實例的析構函數!)
    DWORD exitcode;
    bret = GetExitCodeThread(hthread, &exitcode);//多是STILL_ACTIVE或者退出代碼
    WaitForSingleObject(hthread, INFINITE);
    CloseHandle(hthread);
    hthread = nullptr;

    //建立C++線程
    hthread = (HANDLE)_beginthreadex(nullptr, 0, ThreadProc2, nullptr, 0, nullptr);
    CloseHandle(hthread);
    hthread = nullptr;

    //將GetCurrentThread()獲得的僞句柄轉換成可用的句柄.(記住:句柄表屬於進程,線程共享句柄表)
    bret = DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &hthread, 0, FALSE, DUPLICATE_SAME_ACCESS);
    CloseHandle(hthread);

    system("pause");
    return 0;
}
相關文章
相關標籤/搜索