进程、线程
进程从来不执行任何东西,真正完成代码执行的是线程,而进程只是线程的容器,或者说是线程的执行环境
当创建一个进程时,操作系统会自动创建这个进程的第一个线程,称为主线程
主要函数
CreateMutex();--创建或打开一个命名的或匿名的互斥对象
CreateThread();--创建线程
WaitForSingleObject();--请求共享对象的使用权
ReleaseMutex();--释放指定对象的所有权
例子
// SellTrainTicketsByMutex.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <windows.h>
#include <cstdio>
#include <conio.h>
HANDLE g_hMutex =NULL;
int tickets =100;
DWORD WINAPI Fun1Proc1(LPVOID lpParameter)
{
while(1)
{
WaitForSingleObject(g_hMutex,INFINITE);
if(tickets>0)
{
Sleep(10);
printf("thread1 sell ticket:%d\n",tickets--);
}
else
{
break;
}
ReleaseMutex(g_hMutex);
}
return 0;
}
DWORD WINAPI Fun1Proc2(LPVOID lpParameter)
{
while(1)
{
WaitForSingleObject(g_hMutex,INFINITE);
if(tickets>0)
{
Sleep(10);
printf("thread2 sell ticket:%d\n",tickets--);
}
else
{
break;
}
ReleaseMutex(g_hMutex);
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hThread1,hThread2;
//创建互斥对象
g_hMutex=CreateMutex(NULL,FALSE,NULL);
//创建线程
hThread1=CreateThread(NULL,0,Fun1Proc1,NULL,0,NULL);
hThread2=CreateThread(NULL,0,Fun1Proc2,NULL,0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
_getch();
printf("exit!\n");
return 0;
}