在CreateSemaphore()API中使用lmaxcount参数有什么用?

时间:2013-09-05 07:26:46

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

我正在学习Windows操作系统,而我正在编写标准的消费者生产者问题。我有资源计数的信号量和同步的互斥量。我在CreateSemaphore()中传递了max count 50的值,因此它不应该允许producer创建超过50个资源。但是,当我运行代码时,它远远超出了它。我是否理解使用max count参数错误? 我也粘贴代码。请帮我拍这个问题。

#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);


    }
}

1 个答案:

答案 0 :(得分:2)

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