簡體   English   中英

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

[英]WaitForSingleObject on a semaphore does not wait, returns immediately

我正在嘗試使用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;
}

我到底在做什么錯? 我應該如何使用信號量?

當我打開服務器時,它不會等待客戶端。

CreateSemaphore的文檔

當信號量對象的計數大於零時,將發出信號狀態;在信號量對象的計數等於零時,將不發出信號狀態。 lInitialCount參數指定初始計數。

創建信號量時,您傳遞了lInitialCount=1 並且1 > 0 ,因此會發出信號量信號,並且WaitForSingleObject立即返回。

您大概想創建一個初始計數為0的信號量,以便直到有人調用ReleaseSemaphore時才發出信號。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM