haris
haris

Reputation: 2033

Win32 equivalent API for pthread_cond_wait

I want to know, what would be the Win32 API equivalent to pthread_cond_wait() and pthread_cond_signal()?

Upvotes: 0

Views: 683

Answers (2)

senajoaop
senajoaop

Reputation: 355

The closest equivalent that you'll find in a short answer is SleepConditionVariableCS()and WakeConditionVariable() respectively.

But as you can see in this example in the documentation, it's NOT that straightforward. I encourage you to understand their usage with this simple example, and to bear in mind that it's used in a Critical Section and not with Mutex, as better explained here in this answer.


A simpler and clearer example would be:

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

CONDITION_VARIABLE condFuel;
CRITICAL_SECTION lockFuel;

int fuel = 0;

DWORD WINAPI fuel_filling(LPVOID arg) {

    for (int i = 0; i < 5; i++) {
        EnterCriticalSection(&lockFuel);
        fuel += 30;
        printf("Filled fuel: %d\n", fuel);
        Sleep(1000);
        WakeConditionVariable(&condFuel);
        LeaveCriticalSection(&lockFuel);
    }

    return 0;
}

DWORD WINAPI car(LPVOID arg) {

    EnterCriticalSection(&lockFuel);

    while (fuel < 40) {
        printf("No fuel, waiting...\n");
        SleepConditionVariableCS(&condFuel, &lockFuel, INFINITE);
    }
    fuel -= 40;
    printf("Got fuel, is left: %d\n", fuel);
    Sleep(1000);

    LeaveCriticalSection(&lockFuel);

    return 0;
}

int main(int argc, char** argv) {
    HANDLE tr[6];
    DWORD id[6];

    InitializeConditionVariable(&condFuel);
    InitializeCriticalSection(&lockFuel);

    for (int i = 0; i < 6; i++) {
        if (i == 4 || i == 5) {
            tr[i] = CreateThread(NULL, 0, fuel_filling, NULL, 0, &id[i]);

            if (tr[i] == NULL) {
                printf("CreateThread error: %d\n", GetLastError());
                exit(1);
            }
        }
        else {
            tr[i] = CreateThread(NULL, 0, car, NULL, 0, &id[i]);

            if (tr[i] == NULL) {
                printf("CreateThread error: %d\n", GetLastError());
                exit(1);
            }
        }
    }

    WakeAllConditionVariable(&condFuel);

    WaitForMultipleObjects(6, tr, TRUE, INFINITE);

    for (int i = 0; i < 6; i++) {
        CloseHandle(tr[i]);
    }

    return 0;
}

Upvotes: 0

selbie
selbie

Reputation: 104569

Let me Google that for you: "Win32 Condition Variable"

Top answer leads you to this link on MSDN where it describes the relevant APIs for creating, waiting, and notifying.

Upvotes: -3

Related Questions