信号量上的WaitForSingleObject不等待,立即返回

时间:2013-10-23 17:36:06

标签: c++ windows file-mapping

我正在尝试使用Windows文件映射创建一个简单的客户端 - 服务器程序,并使用信号量。客户端向服务器发送2个号码,服务器计算nr1 + nr2和nr1 * nr2。我尝试了一些东西,但它甚至不适用于1个客户端,我希望它能为更多客户工作。这是代码:

服务器:

#include <windows.h>
#include <stdio.h>
#include <iostream>
using namespace std;

typedef struct {
    int nr1;
    int nr2;
} Mesaj;

int main(int argc, char** argv) {

    Mesaj* mesaj;

    HANDLE createSemaphore = CreateSemaphore(NULL, 1, 1, "Semafor");
    if (createSemaphore == NULL || createSemaphore == INVALID_HANDLE_VALUE) {
        wcout << "Failed to create a semaphore\n";
    } else {
        wcout << "Created the semaphore\n";
    }

    HANDLE hMemory = CreateFileMapping(INVALID_HANDLE_VALUE, NULL,
            PAGE_READWRITE, 0, sizeof(Mesaj), "SharedMemory");

    WaitForSingleObject(createSemaphore, INFINITE);

    mesaj = (Mesaj*) MapViewOfFile(hMemory, FILE_MAP_READ, 0, 0, sizeof(Mesaj));

    printf("The numbers received are: %d, %d\n", mesaj->nr1, mesaj->nr2);

    int produs = mesaj->nr1 * mesaj->nr2;
    int suma = mesaj->nr1 + mesaj->nr2;

    printf("\nSuma numerelor este: %d iar produsul lor este: %d", suma, produs);

    ReleaseSemaphore(createSemaphore, 1, NULL);

    Sleep(INFINITE);

    return 0;
}

客户:

#include <windows.h>
#include <stdio.h>
#include <iostream>
using namespace std;

typedef struct {
    int nr1;
    int nr2;
} Mesaj;

int main(int argc, char** argv) {

    Mesaj* mesaj, *mesaj2;

    mesaj2 = (Mesaj*) malloc(sizeof(Mesaj));

    HANDLE hMemory = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE,
            "SharedMemory");

    if (hMemory == NULL) {
        wcout << "Error at OpenFileMapping\n";
    }

    HANDLE openSemaphore = OpenSemaphore(SEMAPHORE_ALL_ACCESS,TRUE,"Semafor");
    if(openSemaphore != NULL || openSemaphore != INVALID_HANDLE_VALUE){
        wcout<<"the semaphore is opened\n";
    }

    mesaj2 = (Mesaj*) MapViewOfFile(hMemory, FILE_MAP_WRITE, 0, 0,
            sizeof(Mesaj));

    int nr1 = 0, nr2 = 0;
    printf("Give a number: ");
    scanf("%d", &nr1);
    printf("Give another number: ");
    scanf("%d", &nr2);

    mesaj2->nr1 = nr1;
    mesaj2->nr2 = nr2;

    if (mesaj2 == NULL) {
        wcout << "Error\n"
    } else {
        wcout << "I sent " << mesaj2->nr1 << " and " << mesaj2->nr2 << endl;
    }


    system("pause");
    return 0;
}

我究竟做错了什么?我应该如何使用信号量?

1 个答案:

答案 0 :(得分:7)

  

当我打开服务器时,它不会等待客户端。

The documentation for CreateSemaphore

  

信号量对象的状态在其计数大于零时发出信号,在其计数等于零时发出信号。 lInitialCount参数指定初始计数。

您在创建信号量时传递了lInitialCount=1。和1 > 0,所以信号量发出信号,WaitForSingleObject立即返回。

您可能想要创建初始计数为0的信号量,以便在有人呼叫ReleaseSemaphore之前不会发出信号。