自己写了一个类,用于互斥
class CMutex { public: CMutex() { m_lock=CreateMutex(NULL,FALSE,NULL); } ~CMutex(){} void Lock() { WaitForSingleObject(m_lock, INFINITE); } void UnLock() { ReleaseMutex(m_lock); } private: HANDLE m_lock; };
int main(int args,char ** argu[]) { CMutex m_mutex; while(TRUE) { m_mutex.Lock(); printf("a\n"); //m_mutex.UnLock(); } }
#include <stdio.h> #include "Mutex.h" CMutex m_mutex; DWORD WINAPI ThreadProc(LPVOID lpParam) { m_mutex.Lock(); Sleep(3000); m_mutex.UnLock(); Sleep(3000); return 0; } int main(int args,char ** argu[]) { DWORD IDThread; int a=0,b=0; a=GetTickCount(); CreateThread(NULL,0,ThreadProc,NULL,0,&IDThread); Sleep(2);//建立线程需要时间 m_mutex.Lock(); b=GetTickCount(); printf("%dms\n",b-a); m_mutex.UnLock(); system("pause"); }