// Mutex.cpp : Defines the entry point for the console application.
//
/*
互斥的使用
1 互斥的创建
CreateMutex( NULL,
FALSE,//创建后互斥的拥有者,TRUE当前的线程拥有这个线程, FALSE不拥有
NULL );//
2 等候互斥
WaitForSingleObject( hMutex,INFINITE );
3 释放互斥
ReleaseMutex( hMutex );
4 关闭互斥
CloseHandle( hMutex );
5 MFC - CMutex
*/
#include "stdafx.h"
#include "windows.h"
#include "conio.h"
HANDLE hMutex = NULL;
DWORD WINAPI ThreadProc1( LPVOID pVoid )
{
while( 1 )
{
//等候互斥
WaitForSingleObject( hMutex, INFINITE );
printf( "ThreadProc1-------\r\n" );
Sleep( 1000 );
//释放互斥
ReleaseMutex( hMutex );
}
return 0;
}
DWORD WINAPI ThreadProc2( LPVOID pVoid )
{
while( 1 )
{
//等候互斥
WaitForSingleObject( hMutex, INFINITE );
printf( "THreadProc2----------\r\n");
Sleep( 1000 );
//释放互斥
ReleaseMutex( hMutex );
}
return 0;
}
void Mutex()
{
//创建互斥
hMutex = CreateMutex( NULL,
FALSE,
NULL );
// 创建线程
DWORD dwThreadID = 0;
HANDLE hThread[2] = { 0 };
hThread[0] = CreateThread( NULL,
0, ThreadProc1, NULL, 0, &dwThreadID );
hThread[1] = CreateThread( NULL,
0, ThreadProc2, NULL, 0, &dwThreadID );
//等候线程结束
WaitForMultipleObjects( 2, hThread,
TRUE, INFINITE );
//关闭互斥
CloseHandle( hMutex );
}
int main(int argc, char* argv[])
{
Mutex();
getch();
return 0;
}
VC中互斥的使用
最新推荐文章于 2023-04-10 23:43:56 发布