查询信号量对象的计数值 以及例子
时间: 2024-01-03 15:02:58 浏览: 30
要查询信号量对象的计数值,可以使用Windows API中的函数`WaitForSingleObject()`和`WaitForMultipleObjects()`。这些函数会将信号量对象的计数值减一,如果计数值已经为零,则函数会阻塞当前线程,直到有其他线程释放信号量对象。
下面是一个使用信号量对象的例子。该例子创建了两个线程,一个线程负责生产数据,另一个线程负责消费数据,它们之间使用一个信号量对象来同步。
```C++
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#define BUFFER_SIZE 10
HANDLE hSemaphore;
int buffer[BUFFER_SIZE];
int count = 0;
DWORD WINAPI producerThread(LPVOID lpParam) {
int i = 0;
while (i < 20) {
WaitForSingleObject(hSemaphore, INFINITE);
buffer[count++] = i++;
printf("Produced: %d\n", buffer[count-1]);
ReleaseSemaphore(hSemaphore, 1, NULL);
Sleep(500);
}
return 0;
}
DWORD WINAPI consumerThread(LPVOID lpParam) {
int i = 0;
while (i < 20) {
WaitForSingleObject(hSemaphore, INFINITE);
printf("Consumed: %d\n", buffer[--count]);
ReleaseSemaphore(hSemaphore, 1, NULL);
i++;
Sleep(1000);
}
return 0;
}
int main() {
HANDLE hProducerThread, hConsumerThread;
hSemaphore = CreateSemaphore(NULL, BUFFER_SIZE, BUFFER_SIZE, NULL);
if (hSemaphore == NULL) {
printf("Semaphore creation failed\n");
return 1;
}
hProducerThread = CreateThread(NULL, 0, producerThread, NULL, 0, NULL);
hConsumerThread = CreateThread(NULL, 0, consumerThread, NULL, 0, NULL);
WaitForSingleObject(hProducerThread, INFINITE);
WaitForSingleObject(hConsumerThread, INFINITE);
CloseHandle(hSemaphore);
CloseHandle(hProducerThread);
CloseHandle(hConsumerThread);
return 0;
}
```
在上面的例子中,生产者线程和消费者线程都使用了`WaitForSingleObject()`和`ReleaseSemaphore()`函数来同步它们之间对缓冲区的访问。同时,使用计数值为缓冲区大小的信号量对象来限制缓冲区中元素的数量,从而避免了缓冲区溢出和数据竞争的问题。