windows_40_Thread_Mutex 线程 - 互斥
// windows_39_Thread_Mutex.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "windows.h"
//互斥排队等候问题,谁先等候谁先执行
HANDLE g_hMutex = NULL;
DWORD WINAPI ThreadProc1( LPVOID pParam )
{
while (1)
{
//等候互斥量
WaitForSingleObject( g_hMutex ,INFINITE);
printf( "ThreadProc1--------\n" );
Sleep( 500 );
//释放互斥量
ReleaseMutex( g_hMutex );
}
return 0;
}
DWORD WINAPI ThreadProc2( LPVOID pParam )
{
while (1)
{
//等候互斥量
WaitForSingleObject( g_hMutex,INFINITE );
printf( "-------------ThreadProc2\n" );
Sleep( 500 );
//释放互斥量
ReleaseMutex( g_hMutex );
}
return 0;
}
DWORD WINAPI ThreadProc3( LPVOID pParam )
{
while (1)
{
//等候互斥量
WaitForSingleObject( g_hMutex,INFINITE );
printf( "-------ThreadProc3-----------\n" );
Sleep( 500 );
//释放互斥量
ReleaseMutex( g_hMutex );
}
return 0;
}
void Create( )
{
DWORD nThreadID = 0;
HANDLE hThread[3] = { NULL };
hThread[0] = CreateThread( NULL, 0, ThreadProc1, NULL, 0, &nThreadID );
hThread[1] = CreateThread( NULL, 0, ThreadProc2 , NULL, 0, &nThreadID );
hThread[2] = CreateThread( NULL, 0, ThreadProc3 , NULL, 0, &nThreadID );
}
int _tmain(int argc, _TCHAR* argv[])
{
//创建互斥
g_hMutex = CreateMutex( NULL, FALSE, NULL );
Create( );
getchar( );
//关闭互斥
CloseHandle( g_hMutex );
return 0;
}
时间: 2024-10-06 13:21:07