#include "stdafx.h" #include <string> #include <iostream> #include <Windows.h> using namespace std; HANDLE hMutex = NULL; int arr[5] = {1, 2, 3, 4, 5}; DWORD CALLBACK Thread1(LPVOID Param) { while(true) { WaitForSingleObject(hMutex, INFINITE); cout << "Thread1:/t"; for (int i = 0; i < 5; i++) { cout << arr[i] << ' '; Sleep(50); } cout << endl; ReleaseMutex(hMutex); } } DWORD CALLBACK Thread2(LPVOID Param) { while(true) { WaitForSingleObject(hMutex, INFINITE); cout << "Thread2:/t"; for (int i = 0; i < 5; i++) { cout << arr[i] << ' '; Sleep(50); } cout << endl; ReleaseMutex(hMutex); } } int main() { hMutex = CreateMutex(NULL, FALSE, NULL); CreateThread(NULL, 0 ,Thread1, NULL, NULL, NULL); CreateThread(NULL, 0 ,Thread2, NULL, NULL, NULL); while(true) { Sleep(100); } return 0; }
互斥是有线程所有权的
hMutex = CreateMutex(NULL, FALSE, NULL);
FALSE:不为任何线程所有,但他现在也是激发的
TRUE:当前的创建线程所有,默认不激发