一个进程相当于你写了的一个程序正在内存中运行,而这个进程内至少有一个主线程,C++就是main(),还有辅助线程,当然一旦主线程结束了,辅助线程就都结束了,这样就可以比较清晰地理解,进程是资源分配的基本单位,而线程,是共用进程中的资源的,同时操作系统就给了进程一部分内存堆和cpu处理的时间。
下面的函数可以观察两个辅助线程的运行情况
下面的程序有两个辅助线程,没有临界资源
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <windows.h> #include<stdio.h> #include<stdlib.h> #include<iostream> #include<string.h> #include<assert.h> #include<windows.h> #include <process.h> #include<iostream> using namespace std; DWORD WINAPI Fun1Proc(LPVOID lpParameter);//thread data DWORD WINAPI Fun2Proc(LPVOID lpParameter);//thread data int index=0; int tickets=100; HANDLE hMutex; void main() { HANDLE hThread1; HANDLE hThread2; //创建线程 hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL); hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL); CloseHandle(hThread1); CloseHandle(hThread2); WaitForSingleObject(hMutex,INFINITE); Sleep(4000); } //线程1的入口函数 DWORD WINAPI Fun1Proc(LPVOID lpParameter)//thread data { while (true) { if (tickets>0) { Sleep(10); cout<<"thread1 sell ticket :"<<tickets--<<endl; } else break; } return 0; } //线程2的入口函数 DWORD WINAPI Fun2Proc(LPVOID lpParameter)//thread data { while (true) { if (tickets>0) { Sleep(1); cout<<"thread2 sell ticket :"<<tickets--<<endl; } else break; } return 0; }
当一个线程sleep的时候,cpu就去响应其他线程了,这可以说提高了资源利用率
下面的程序有临界资源(原型:两个窗口卖火车票)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <windows.h> #include<stdio.h> #include<stdlib.h> #include<iostream> #include<string.h> #include<assert.h> #include<windows.h> #include <process.h> #include<iostream> using namespace std; DWORD WINAPI Fun1Proc(LPVOID lpParameter);//thread data DWORD WINAPI Fun2Proc(LPVOID lpParameter);//thread data int index=0; int tickets=100; HANDLE hMutex; void main() { HANDLE hThread1; HANDLE hThread2; //创建线程 hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL); hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL); CloseHandle(hThread1); CloseHandle(hThread2); //创建互斥对象 hMutex=CreateMutex(NULL,TRUE,"tickets"); ReleaseMutex(hMutex); if (hMutex) { if (ERROR_ALREADY_EXISTS==GetLastError()) { cout<<"only one instance can run!"<<endl; return; } } WaitForSingleObject(hMutex,INFINITE); ReleaseMutex(hMutex); ReleaseMutex(hMutex); Sleep(4000); } //线程1的入口函数 DWORD WINAPI Fun1Proc(LPVOID lpParameter)//thread data { while (true) { WaitForSingleObject(hMutex,INFINITE); if (tickets>0) { printf("thread1 sell ticket :%d\n",tickets--); ReleaseMutex(hMutex); Sleep(500); } else{ break; } } return 0; } //线程2的入口函数 DWORD WINAPI Fun2Proc(LPVOID lpParameter)//thread data { while (true) { WaitForSingleObject(hMutex,INFINITE); if (tickets>0) { printf("thread2 sell ticket :%d\n",tickets--); ReleaseMutex(hMutex); Sleep(200); } else break; } return 0; }