程序是存储在磁盘上的代码的集合,它不能占用系统资源,不能调度操作系统.
进程是程序的一次运行路径,32位进程在系统中占有4GB的虚拟内存,其中有2GB是内核对象,2GB是存放代码,进程在4GB的内存地址中运行,直到结束后销毁.通过内核对象提供的接口指针,操作系统与进程通信..
线程是在进程的地址空间中执行的一个任务,它在进程中占有很小的地址空间,线程与线程之间通信是很容易的,使用多线程比使用多进程要节省开销.一个进程中可以有多个线程,当一个进程创建是一个主线程也被创建,所有的创建的新线程多在主线程中运行,当主线程结束时其他线程也将结束,如果新线程在创建后没有在主线程中关闭CloseHandle()的话当主线程结束后新线程内存仍然没有释放.
创建线程:
HANDLE CreateThread(
LPSECURITY_ATTRIBUTES lpThreadAttributes,
DWORD dwStackSize,
LPTHREAD_START_ROUTINE lpStartAddress,
LPVOID lpParameter,
DWORD dwCreationFlags,
LPDWORD lpThreadId);
新线程入口:
DWORD WINAPI ThreadProc(
LPVOID lpParameter); ///ThreadProc的名字是可以改变的
Parameters
-
lpThreadAttributes
- Ignored. Must be NULL. dwStackSize
- Ignored. The default stack size for a thread is determined by the linker setting /STACK. lpStartAddress
- Long pointer to the application-defined function of type LPTHREAD_START_ROUTINE to be executed by the thread and represents the starting address of the thread. For more information on the thread function, see ThreadProc. lpParameter
- Long pointer to a single 32-bit parameter value passed to the thread. dwCreationFlags
-
Specifies flags that control the creation of the thread.
Value Description CREATE_SUSPENDED The thread is created in a suspended state, and will not run until the ResumeThread function is called. 0 The thread runs immediately after creation.
lpThreadId
-
Long pointer to a 32-bit variable that receives the thread identifier.
If this parameter is NULL, the thread identifier is not returned.
-
实例:
-
DWORD WINAPI ThreadProc(
LPVOID lpParameter); -
{}
-
HANDLE hThread1;
-
hThread1=CreateThread(NULL,0,ThreadPro1,NULL,0,NULL);
-
DWORD WINAPI ThreadProc(
LPVOID lpParameter); -
{
-
return 0;
-
}
结束线程句柄:
BOOL CloseHandle(
HANDLE hObject // handle to object
);
当在单CPU上创建多线程的程序时,多线程并不是真正的同步运行的,只是由于线程是按CPU时间片交替
执行的,所以我们没有察觉罢了,当在多CPU上执行多线程时,就可以实现真正的同步运行了.
为了在主线程main()或WinMain()里运行多线程,必须让主线程Sleep()一段时间,否则还没有执行其他线程,
主线程就提前结束了,用Sleep()来休眠主线程时它不占用资源.系统在给线程分配时间片的时候是按优先
级给线程分配的.