#include <Windows.h> #include <process.h> #include <stdio.h> HANDLE hMutex; //互斥对象 void ProcessTask(void * args) { int a = 0; WaitForSingleObject(hMutex, INFINITE); while ( a < 100) printf("_beginthread %d\n", a++); ReleaseMutex(hMutex); //结束后会自动调用_endtrhead } unsigned int _stdcall ProcessTask2(void * args) { int a = 0; WaitForSingleObject(hMutex, INFINITE); while ( a < 100) printf("_beginthreadex %d\n", a++); ReleaseMutex(hMutex); //如果不释放, 线程结束时, 系统也会释放 //结束后会自动调用_endtrheadex return 0; } DWORD WINAPI ThreadProc(LPVOID lpParameter) { int a = 0; WaitForSingleObject(hMutex, INFINITE); while ( a < 100) printf("CreateThread %d\n", a++); ReleaseMutex(hMutex); return 0; } int main() { hMutex = CreateMutex(NULL, FALSE, "tickets"); if(hMutex) { if(ERROR_ALREADY_EXISTS == GetLastError()) { printf("one instance has exist\n"); system("pause"); return 0; } } _beginthread(ProcessTask, 0, 0); _beginthreadex(NULL, 0, ProcessTask2, NULL, 0, 0); Sleep(3000); DWORD threadId; HANDLE hThread3 = CreateThread(0, 0, ThreadProc, 0, 0, &threadId); //不建议使用, 在处理c库的时间类函数会内在泄漏大约70-80字节 //创建匿名互斥对象 //hMutex = CreateMutex(NULL, FALSE, NULL); //第二个参数参数初始化时当前线是否拥有互斥对象, 如果设置发TRUE, 可以用ReleaseMutex释放 //创建一个命名互斥对象可以判断实例是否在运行 CloseHandle(hThread3); system("pause"); return 0; }