标签:create 影响 close ret color print ram eth try
// Mutex.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <windows.h> #include <assert.h> //Mutex的OpenMutex()与ReleaseMutex()必须线程配对的.不配对线程的操作会报错(Attempt Release Mutex not owner by caller). //Mutex对象的句柄所在线程退出,会自动释放&关闭句柄,且Mutex对象会置为有信号 LONG g_i0{}; LONG g_i1{}; DWORD WINAPI ThreadProc1(LPVOID lpThreadParameter); DWORD WINAPI ThreadProc2(LPVOID lpThreadParameter); int main() { HANDLE hMutex = CreateMutexA(0, 0, "Mutex0"); // Mutex创建出来就是有信号的 if (!hMutex) { assert(0); } HANDLE hThread[2]{}; hThread[0] = CreateThread(0, 0, ThreadProc1, 0, 0, 0); hThread[1] = CreateThread(0, 0, ThreadProc2, 0, 0, 0); WaitForMultipleObjects(2, hThread, TRUE, INFINITE); CloseHandle(hThread[0]); CloseHandle(hThread[1]); CloseHandle(hMutex); printf("%d\n", g_i0); printf("%d\n", g_i1); system("pause"); return 0; } DWORD WINAPI ThreadProc1(LPVOID lpThreadParameter) { HANDLE hMutex = OpenMutexA(MUTEX_ALL_ACCESS, 0, "Mutex0"); // 不对信号产生影响 if (!hMutex) { assert(0); } WaitForSingleObject(hMutex, INFINITE); // 有信号变无信号,没信号阻塞 for (int i = 0; i < 1000000; i++) { g_i0++; g_i1++; } //ReleaseMutex(hMutex); // 无信号变为有信号 //CloseHandle(hMutex); return 0; } DWORD WINAPI ThreadProc2(LPVOID lpThreadParameter) { HANDLE hMutex = OpenMutexA(MUTEX_ALL_ACCESS, 0, "Mutex0"); if (!hMutex) { assert(0); } WaitForSingleObject(hMutex, INFINITE); for (int i = 0; i < 1000000; i++) { g_i0++; g_i1++; } ReleaseMutex(hMutex); CloseHandle(hMutex); return 0; }
标签:create 影响 close ret color print ram eth try
原文地址:http://www.cnblogs.com/Spobt/p/7212014.html