HANDLE hSemaphore; cout<<1<<endl; hSemaphore = CreateSemaphore( NULL, 0, 10000, NULL); ReleaseSemaphore(hSemaphore, 1, NULL); ReleaseSemaphore(hSemaphore, 1, NULL); DWORD dwWaitResult = WaitForSingleObject(hSemaphore, INFINITE); cout<<2<<endl; WaitForSingleObject(hSemaphore, INFINITE); cout<<3<<endl; WaitForSingleObject(hSemaphore, INFINITE); cout<<4<<endl;
输出
1
2
3
_
//CreateSemaphore( NULL, 0, 100, NULL); 初始信号为0
//ReleaseSemaphore(hSemaphore, 1, NULL);信号加1
//WaitForSingleObject(hSemaphore, INFINITE);阻塞式等待,返回时,信号减1
线程间的通知:
如果线程B需要线程A的数据。
当线程A的数据增加时,可以ReleaseSemaphore(hSemaphore, 1, NULL);
线程B使用WaitForSingleObject(hSemaphore, INFINITE);来判断线程A有无数据
时间: 2024-10-28 19:45:39