#include<iostream> #include"windows.h" using namespace std; DWORD WINAPI FUN1(LPVOID lpParameter); DWORD WINAPI FUN2(LPVOID lpParameter); HANDLE hSemaphore=CreateSemaphore(NULL,1,1,NULL); int main() { HANDLE thread1; HANDLE thread2; thread1=CreateThread(NULL,0,FUN1,NULL,0,NULL); thread2=CreateThread(NULL,0,FUN2,NULL,0,NULL); CloseHandle(thread1); CloseHandle(thread2); Sleep(100000000); return 0; } DWORD WINAPI FUN1(LPVOID lpParameter) { while(true) { if(WaitForSingleObject(hSemaphore,INFINITE)) { cout<<"thread1 got signal"<<endl; Sleep(2); ReleaseSemaphore(hSemaphore,1,NULL); } else {cout<<"thread1 lose signal"<<endl; } } } DWORD WINAPI FUN2(LPVOID lpParameter) { while(true) { if(WaitForSingleObject(hSemaphore,INFINITE)) { cout<<"thread2 got signal"<<endl; Sleep(3); ReleaseSemaphore(hSemaphore,1,NULL); } else {cout<<"thread2 lose signal"<<endl; } } } //出现乱码,并且没有任何一个线程获得信号非常奇怪
时间: 2024-09-28 04:48:42