一、线程概念
(1).Windows线程是可以执行的代码的实例,系统是以线程为单位调度程序,一个程序当中可以有多个线程,实现多任务的处理
(2).Windows线程的特点:
- 线程都具有一个ID
- 每个线程都具有自己的内存栈
- 同一进程中的线程使用同一个地址空间
(3).线程的调度:操作系统将CPU的执行时间划分成时间片,依次根据时间片执行不同的线程,线程轮询:线程A->线程B->线程A...
二、线程的使用
1.创建线程
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 //创建成功,返回线程的ID ); 创建成功,返回线程句柄
2.定义线程处理函数
DWORD WINAPI ThreadProc( LPVOID lpParameter //创建线程时,传递给线程的参数 );
示例代码:
#include <Windows.h> #include <iostream> using namespace std; DWORD CALLBACK ThreadProc(LPVOID lpThreadParameter) { char* szText = (char*)lpThreadParameter; while (true) { cout << szText << endl; Sleep(1000); } return 0; } int main() { const char* pszText = "********"; DWORD nID = 0; HANDLE hThread = CreateThread(NULL, 0, ThreadProc, (LPVOID)pszText, 0, &nID); if (hThread == NULL) { cout << "create thread failed" << GetLastError(); } system("pause"); return 1; }
三、线程挂起和销毁
(1).线程的挂起
DWORD SuspendThread( HANDLE hThread //handle to thread );
(2).线程的唤醒
DWORD ResumenThread( HANDLE hThread //handle to thread );
示例代码:
#include <Windows.h> #include <iostream> using namespace std; DWORD CALLBACK ThreadProc(LPVOID lpThreadParameter) { char* szText = (char*)lpThreadParameter; while (true) { cout << szText << endl; Sleep(1000); } return 0; } DWORD CALLBACK ThreadProc1(LPVOID lpThreadParameter) { char* szText = (char*)lpThreadParameter; while (true) { cout << szText << endl; Sleep(1000); } return 0; } int main() { const char* pszText = "********"; DWORD nID = 0; //线程立即执行 HANDLE hThread = CreateThread(NULL, 0, ThreadProc, (LPVOID)pszText, 0, &nID); if (hThread == NULL) { cout << "create thread failed" << GetLastError(); } const char* pszText1 = "--------"; DWORD nID1 = 0; //线程挂起 HANDLE hThread1 = CreateThread(NULL, 0, ThreadProc1, (LPVOID)pszText1, CREATE_SUSPENDED, &nID1); if (hThread1 == NULL) { cout << "create thread failed" << GetLastError(); } getchar(); SuspendThread(hThread); ResumeThread(hThread1); getchar(); return 1; }
标签:char,lpThreadParameter,编程,LPVOID,Win32,线程,DWORD,include From: https://www.cnblogs.com/TechNomad/p/17706797.html