c - CreateSemaphore() API 中的 lmaxcount 参数有什么用?

标签 c windows visual-studio visual-c++

我正在学习 Windows 操作系统,并且正在编写标准的消费者生产者问题。我有一个用于资源计数的信号量和一个用于同步的互斥体。我已经在 CreateSemaphore() 中传递了最大计数 50 的值,因此它不应允许生产者创建超过 50 个资源。但当我运行代码时,它远远超出了这个范围。我是否错误地理解了最大计数参数的使用? 我也贴一下代码。请帮我解决这个问题。

#include<stdio.h>
#include<windows.h>

DWORD WINAPI consumerThread(LPVOID args);
DWORD WINAPI producerThread(LPVOID args);

int shared;
HANDLE hMutex;
HANDLE hSemaphore;
HANDLE hConsumer;
HANDLE hProducer;
DWORD dwConsumerId,dwProducerId;

#define MAX_COUNT 50
#define MIN_COUNT 0
int main()
{
    if(!(hMutex=CreateMutex(NULL,0,NULL)))
    {
        puts("Error:: unable to create Mutex!!");
        ExitProcess(GetLastError());
    }
    if(!(hSemaphore=CreateSemaphore(NULL,MIN_COUNT,MAX_COUNT,NULL)))
    {
        puts("Error:: unable to create Semaphore object!!");
        ExitProcess(GetLastError());
    }
    if(!(hConsumer=CreateThread(NULL,0,consumerThread,NULL,0,&dwConsumerId)))
    {
        puts("Error:: unable to create consumer Thread!!");
        ExitProcess(GetLastError());
    }
    if(!(hProducer=CreateThread(NULL,0,producerThread,NULL,0,&dwProducerId)))
    {
        puts("Error:: unable to create producer Thread!!");
        ExitProcess(GetLastError());
    }
    WaitForSingleObject(hConsumer,INFINITE);
    WaitForSingleObject(hProducer,INFINITE);
    CloseHandle(hMutex);
    CloseHandle(hSemaphore);
    CloseHandle(hConsumer);
    CloseHandle(hProducer);
    return 0;
}

DWORD WINAPI consumerThread(LPVOID args)
{

    while(1)
    {
        WaitForSingleObject(hSemaphore,INFINITE);
        WaitForSingleObject(hMutex,INFINITE);
        shared--;
        printf("Consumer  = %d\n",shared);
        ReleaseMutex(hMutex);
        //Sleep(1000);
    }
}

DWORD WINAPI producerThread(LPVOID args)
{
    if(!SetThreadPriority(hProducer,THREAD_PRIORITY_HIGHEST))
    {
        printf("Error:: Unable to set the thread priority level!!\n");
        ExitProcess(GetLastError());
    }
    while(1)
    {
        WaitForSingleObject(hMutex,INFINITE);
        shared++;
        printf("Producer =%d\n",shared);
        ReleaseMutex(hMutex);
            ReleaseSemaphore(hSemaphore,1,NULL);


    }
}

最佳答案

这个问题在 @Hans Passant 和 @Igor Tandetnik 的评论中得到了回答。要点是,如果您尝试将信号量的值增加到超过 lmaxcount 参数中指定的值,ReleaseSemaphore() API 将失败,而不是阻塞调用线程。所以你应该检查它的返回值,因为我没有这样做并陷入了麻烦。 :)

关于c - CreateSemaphore() API 中的 lmaxcount 参数有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18630235/

相关文章:

c# - 在 Visual Studio 2015 中实现接口(interface)时自动用#region 包围生成的代码

c# - 在设计器中打开自定义用户控件时,Visual Studio Professional 15.9.2 崩溃

c++ - 在内存中复制字节时,字节顺序是否有影响?

c - scanf 不断被跳过

c - 在对程序进行 n 次模拟时打印到文件(C 语言)

windows - Windows Server 2003 中的最大线程数是多少?

asp.net - 自定义 UserControl 未在 ASP.NET 中注册

c++ - 使用 strlen() 在堆栈中分配缓冲区

c++ - 如何计算 char 数组中元素的数量?

python - 我无法删除刚从 python 中的 zip 文件中提取的文件夹