简体   繁体   中英

Concurrency issue (Deadlock?)

I have one server and multiple clients. The server uses the first function through it's main function, and the clients call the second function through a thread (one client uses one thread to read in an infinite loop).

This is for a school assignment, the final purpose is to pass on the gameData struct through shared memory, to recreate the Arkanoid Game

BOOL EmitBroadcast(JOGO * structure) {//called by the server
    WaitForSingleObject(hMutexServer, WAIT_ABANDONED);
    structure->numPlayersAtivosAux = structure->numPlayersAtivos;

    memcpy(pBufGameData, structure, sizeof(JOGO));

    ReleaseMutex(hMutexServer);
    SetEvent(hServerHasWritten);

    return TRUE;
}

JOGO ReceiveBroadcast(JOGO * structure) {//used by the client's thread in loop
    //R/W de Michel Raynal 
    WaitForSingleObject(hServerHasWritten, INFINITE);
    WaitForSingleObject(hMutexCliente, INFINITE);//lock r

    structure= &(*pBufGameData);

    if (structure->numPlayersAtivosAux == structure->numPlayersAtivos) {
        WaitForSingleObject(hMutexServer, INFINITE);//lock g
    }

    structure= pBufGameData;

    (structure->numPlayersAtivosAux)--;
    memcpy(pBufGameData, structure, sizeof(JOGO));

    if (structure->numPlayersAtivosAux == 0) {
        ReleaseMutex(hMutexServer);//unlock g
        ResetEvent(hServerHasWritten);
    }

    ReleaseMutex(hMutexCliente);//unlock r

    return * structure;
}

void receiveLoop(LPVOID lParam) {//client thread loop function
    JOGO * gameInfoIn = (JOGO *)lParam;

    do {
        *gameInfoIn = ReceiveBroadcast(gameInfoIn);
        _tprintf(TEXT("\n%d"), gameInfoIn->vidas);

        Sleep(300);//testing purposes
    } while (closeThreadReceiveLoop || gameInfoIn->vidas != 0);
}

When I open more than one client and the server, after 1 successful read of each client, the server sends correctly and one client locks in the WaitForSingleObject(hMutexServer, INFINITE); line. Expected result is multiple successful reads.

Ok, so as pointed out by Michael Chourdakis in the comments, I had a wrongful parameter in the WaitForSingleObject function. I worked this around by adding an event to the first client that blocks the serverMutex.

That makes the first client thread wait for the remaining client threads to finish. The last client thread triggers the event and the first client is able to terminate and release the server mutex lock.

Thanks for the comments Michael Chourdakis and OznOg.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM