进程:是程序的执行过程,具有动态性,即运行的程序就叫进程,不运行就叫程序 ,每个进程包含一到多个线程。
线程:系统中的最小执行单元,同一进程中有多个线程,线程可以共享资源,一旦出现共享资源,必须注意线程安全!!
先阐述一下进程和线程的概念和区别,这是一个许多大学老师也讲不清楚的问题。
进程(Process)是具有一定独立功能的程序关于某个数据集合上的一次运行活动,是系统进行资源分配和调度的一个独立单位。程序只是一组指令的有序集合,它本身没有任何运行的含义,只是一个静态实体。而进程则不同,它是程序在某个数据集上的执行,是一个动态实体。它因创建而产生,因调度而运行,因等待资源或事件而被处于等待状态,因完成任务而被撤消,反映了一个程序在一定的数据集上运行的全部动态过程。
线程(Thread)是进程的一个实体,是CPU调度和分派的基本单位。线程不能够独立执行,必须依存在应用程序中,由应用程序提供多个线程执行控制。
线程和进程的关系是:线程是属于进程的,线程运行在进程空间内,同一进程所产生的线程共享同一内存空间,当进程退出时该进程所产生的线程都会被强制退出 并清除。线程可与属于同一进程的其它线程共享进程所拥有的全部资源,但是其本身基本上不拥有系统资源,只拥有一点在运行中必不可少的信息(如程序计数器、 一组寄存器和栈)。
根据进程与线程的设置,操作系统大致分为如下类型:
(1)单进程、单线程,MS-DOS大致是这种操作系统;
(2)多进程、单线程,多数UNIX(及类UNIX的LINUX)是这种操作系统;
(3)多进程、多线程,Win32(Windows NT/2000/XP等)、Solaris 2.x和OS/2都是这种操作系统;
(4)单进程、多线程,VxWorks是这种操作系统。
在操作系统中引入线程带来的主要好处是:
(1)在进程内创建、终止线程比创建、终止进程要快;
(2)同一进程内的线程间切换比进程间的切换要快,尤其是用户级线程间的切换。
另外,线程的出现还因为以下几个原因:
(1)并发程序的并发执行,在多处理环境下更为有效。一个并发程序可以建立一个进程,而这个并发程序中的若干并发程序段就可以分别建立若干线程,使这些线程在不同的处理机上执行。
(2)每个进程具有独立的地址空间,而该进程内的所有线程共享该地址空间。这样可以解决父子进程模型中,子进程必须复制父进程地址空间的问题。
(3)线程对解决客户/服务器模型非常有效。
Win32进程间通信的方式主要有:
(1)剪贴板(Clip Board);
(2)动态数据交换(Dynamic Data Exchange);
(3)部件对象模型(Component Object Model);
(4)文件映射(File Mapping);
(5)邮件槽(Mail Slots);
(6)管道(Pipes);
(7)Win32套接字(Socket);
(8)远程过程调用(Remote Procedure Call);
(9)WM_COPYDATA消息(WM_COPYDATA Message)。
2、获取进程信息
在WIN32中,可使用在PSAPI .DLL中提供的Process status Helper函数帮助我们获取进程信息。
(1)EnumProcesses()函数可以获取进程的ID,其原型为:
BOOL EnumProcesses(DWORD * lpidProcess, DWORD cb, DWORD*cbNeeded); |
参数lpidProcess:一个足够大的DWORD类型的数组,用于存放进程的ID值;
参数cb:存放进程ID值的数组的最大长度,是一个DWORD类型的数据;
参数cbNeeded:指向一个DWORD类型数据的指针,用于返回进程的数目;
函数返回值:如果调用成功,返回TRUE,同时将所有进程的ID值存放在lpidProcess参数所指向的数组中,进程个数存放在cbNeeded参数所指向的变量中;如果调用失败,返回FALSE。
(2)GetModuleFileNameExA()函数可以实现通过进程句柄获取进程文件名,其原型为:
DWORD GetModuleFileNameExA(HANDLE hProcess, HMODULE hModule,LPTSTR lpstrFileName, DWORD nsize); |
参数hProcess:接受进程句柄的参数,是HANDLE类型的变量;
参数hModule:指针型参数,在本文的程序中取值为NULL;
参数lpstrFileName:LPTSTR(表示指向字符/字符串的指针)类型的指针,用于接受主调函数传递来的用于存放进程名的字符数组指针;
参数nsize:lpstrFileName所指数组的长度;
函数返回值:如果调用成功,返回一个大于0的DWORD类型的数据,同时将hProcess所对应的进程名存放在lpstrFileName参数所指向的数组中;加果调用失败,则返回0。
通过下列代码就可以遍历系统中的进程,获得进程列表:
//获取当前进程总数 EnumProcesses(process_ids, sizeof(process_ids), &num_processes); //遍历进程 for (int i = 0; i < num_processes; i++) { //根据进程ID获取句柄 process[i] = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, 0, process_ids[i]); //通过句柄获取进程文件名 if (GetModuleFileNameExA(process[i], NULL, File_name, sizeof(fileName))) cout << fileName << endl; } |
DWORD WaitForSingleObject( HANDLE hHandle, // 等待对象的句柄 DWORD dwMilliseconds // 等待毫秒数,INFINITE表示无限等待 ); |
DWORD WaitForMultipleObjects(DWORD nCount,const HANDLE* pHandles,BOOL bWaitAll,DWORD dwMilliseconds); |
BOOL CloseHandle(HANDLE hObject); |
C运行时库 | 库文件 |
Single thread(static link) | libc.lib |
Debug single thread(static link) | Libcd.lib |
MultiThread(static link) | libcmt.lib |
Debug multiThread(static link) | libcmtd.lib |
MultiThread(dynamic link) | msvert.lib |
Debug multiThread(dynamic link) | msvertd.lib |
error LNK2001: unresolved external symbol __endthreadex error LNK2001: unresolved external symbol __beginthreadex |
UINT ThreadFunction(LPVOID pParam) { //线程处理代码 return0; } |
while(1) { WaitForSingleObject(…,…);//或WaitForMultipleObjects(…) //Do something } |
#include "windows.h" #include <process.h> class ExampleTask { public: void taskmain(LPVOID param); void StartTask(); }; void ExampleTask::taskmain(LPVOID param) {} void ExampleTask::StartTask() { _beginthread(taskmain,0,NULL); } int main(int argc, char* argv[]) { ExampleTask realTimeTask; realTimeTask.StartTask(); return 0; } |
error C2664: ‘_beginthread‘ : cannot convert parameter 1 from ‘void (void *)‘ to ‘void (__cdecl *)(void *)‘ None of the functions with this name in scope match the target type |
#include "windows.h" #include <process.h> class ExampleTask { public: void taskmain(LPVOID param); }; void ExampleTask::taskmain(LPVOID param) {} int main(int argc, char* argv[]) { ExampleTask realTimeTask; _beginthread(ExampleTask::taskmain,0,NULL); return 0; } |
error C2664: ‘_beginthread‘ : cannot convert parameter 1 from ‘void (void *)‘ to ‘void (__cdecl *)(void *)‘ None of the functions with this name in scope match the target type |
#include "windows.h" #include <process.h> class ExampleTask { public: void static taskmain(LPVOID param); void StartTask(); }; void ExampleTask::taskmain(LPVOID param) {} void ExampleTask::StartTask() { _beginthread(taskmain,0,NULL); } int main(int argc, char* argv[]) { ExampleTask realTimeTask; realTimeTask.StartTask(); return 0; } 和 #include "windows.h" #include <process.h> class ExampleTask { public: void static taskmain(LPVOID param); }; void ExampleTask::taskmain(LPVOID param) {} int main(int argc, char* argv[]) { _beginthread(ExampleTask::taskmain,0,NULL); return 0; } |
#include "windows.h" #include <process.h> class ExampleTask { public: friend void taskmain(LPVOID param); void StartTask(); }; void taskmain(LPVOID param) { ExampleTask * pTaskMain = (ExampleTask *) param; //通过pTaskMain指针引用 } void ExampleTask::StartTask() { _beginthread(taskmain,0,this); } int main(int argc, char* argv[]) { ExampleTask realTimeTask; realTimeTask.StartTask(); return 0; } |
HANDLE CreateThread( LPSECURITY_ATTRIBUTES lpThreadAttributes,//Pointer to a SECURITY_ATTRIBUTES structure SIZE_T dwStackSize, //Initial size of the stack, in bytes. LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, //Pointer to a variable to be passed to the thread DWORD dwCreationFlags, //Flags that control the creation of the thread LPDWORD lpThreadId //Pointer to a variable that receives the thread identifier ); |
uintptr_t _beginthread( void( __cdecl *start_address )( void * ), //Start address of routine that begins execution of new thread unsigned stack_size, //Stack size for new thread or 0. void *arglist //Argument list to be passed to new thread or NULL ); uintptr_t _beginthreadex( void *security,//Pointer to a SECURITY_ATTRIBUTES structure unsigned stack_size, unsigned ( __stdcall *start_address )( void * ), void *arglist, unsigned initflag,//Initial state of new thread (0 for running or CREATE_SUSPENDED for suspended); unsigned *thrdaddr ); |
VOID ExitThread(UINT fuExitCode ); |
BOOL TerminateThread(HANDLE hThread,DWORD dwExitCode); |
DWORD ResumeThread(HANDLE hThread); |
DWORD SuspendThread(HANDLE hThread); |
BOOL SetThreadPriority(HANDLE hThread, int nPriority); |
VOID Sleep(DWORD dwMilliseconds); |
Int GetThreadPriority (HANDLE hThread); |
BOOL WINAPI GetExitCodeThread( HANDLE hThread, LPDWORD lpExitCode ); |
BOOL WINAPI GetThreadContext( HANDLE hThread, LPCONTEXT lpContext ); BOOL WINAPI SetThreadContext( HANDLE hThread, CONST CONTEXT *lpContext ); |
#define WIN32_LEAN_AND_MEAN #include <stdio.h> #include <stdlib.h> #include <windows.h> #include <conio.h> DWORD WINAPI ThreadFunc(LPVOID); int main() { HANDLE hThrd1; HANDLE hThrd2; DWORD exitCode1 = 0; DWORD exitCode2 = 0; DWORD threadId; hThrd1 = CreateThread(NULL, 0, ThreadFunc, (LPVOID)1, 0, &threadId ); if (hThrd1) printf("Thread 1 launched\n"); hThrd2 = CreateThread(NULL, 0, ThreadFunc, (LPVOID)2, 0, &threadId ); if (hThrd2) printf("Thread 2 launched\n"); // Keep waiting until both calls to GetExitCodeThread succeed AND // neither of them returns STILL_ACTIVE. for (;;) { printf("Press any key to exit..\n"); getch(); GetExitCodeThread(hThrd1, &exitCode1); GetExitCodeThread(hThrd2, &exitCode2); if ( exitCode1 == STILL_ACTIVE ) puts("Thread 1 is still running!"); if ( exitCode2 == STILL_ACTIVE ) puts("Thread 2 is still running!"); if ( exitCode1 != STILL_ACTIVE && exitCode2 != STILL_ACTIVE ) break; } CloseHandle(hThrd1); CloseHandle(hThrd2); printf("Thread 1 returned %d\n", exitCode1); printf("Thread 2 returned %d\n", exitCode2); return EXIT_SUCCESS; } /* * Take the startup value, do some simple math on it, * and return the calculated value. */ DWORD WINAPI ThreadFunc(LPVOID n) { Sleep((DWORD)n*1000*2); return (DWORD)n * 10; } |
#define WIN32_LEAN_AND_MEAN #include <stdio.h> #include <stdlib.h> #include <windows.h> DWORD WINAPI ThreadFunc(LPVOID); int main() { HANDLE hThrd; DWORD threadId; int i; for (i = 0; i < 5; i++) { hThrd = CreateThread(NULL, 0, ThreadFunc, (LPVOID)i, 0, &threadId); if (hThrd) { printf("Thread launched %d\n", i); CloseHandle(hThrd); } } // Wait for the threads to complete. Sleep(2000); return EXIT_SUCCESS; } DWORD WINAPI ThreadFunc(LPVOID n) { int i; for (i = 0; i < 10; i++) printf("%d%d%d%d%d%d%d%d\n", n, n, n, n, n, n, n, n); return 0; } |
#include <Win32.h> #include <stdio.h> #include <process.h> unsigned Counter; unsigned __stdcall SecondThreadFunc(void *pArguments) { printf("In second thread...\n"); while (Counter < 1000000) Counter++; _endthreadex(0); return 0; } int main() { HANDLE hThread; unsigned threadID; printf("Creating second thread...\n"); // Create the second thread. hThread = (HANDLE)_beginthreadex(NULL, 0, &SecondThreadFunc, NULL, 0, &threadID); // Wait until second thread terminates WaitForSingleObject(hThread, INFINITE); printf("Counter should be 1000000; it is-> %d\n", Counter); // Destroy the thread object. CloseHandle(hThread); } |
原文:https://www.cnblogs.com/chaoyingLi/p/11236070.html