#include <iostream> #include <windows.h> using namespace std; HANDLE hMutex; //public : // volatile a; DWORD WINAPI Fun(LPVOID lpParamter) { while (1) { WaitForSingleObject(hMutex, INFINITE); cout << "Fun display!" << endl; Sleep(1000); ReleaseMutex(hMutex); } } int main() { HANDLE hThread = CreateThread(NULL, 0, Fun, NULL, 0, NULL); hMutex = CreateMutex(NULL, FALSE,NULL); CloseHandle(hThread); while (1) { WaitForSingleObject(hMutex, INFINITE); cout << "main display!" << endl; Sleep(2000); ReleaseMutex(hMutex); } return 0; }
创建多个子线程
HANDLE handle[THREAD_NUM]; for (int i = 0; i < THREAD_NUM; i++) handle[i] = (HANDLE)_beginthreadex(NULL, 0, ThreadFun, NULL, 0, NULL);
参考: