Problem: Multiple threads accessing shared data without synchronization, leading to inconsistent results.

·

Solution: Use a CRITICAL_SECTION to serialize access to shared resources.

#include <windows.h>
#include <iostream>

constexpr int THREAD_COUNT = 2;
constexpr int ITERATIONS = 100000;

int sharedCounter = 0;
CRITICAL_SECTION cs;

DWORD WINAPI IncrementCounter(LPVOID lpParam) {
    for (int i = 0; i < ITERATIONS; ++i) {
        EnterCriticalSection(&cs);
        sharedCounter++; // Critical section
        LeaveCriticalSection(&cs);
    }
    return 0;
}

int main() {
    InitializeCriticalSectionAndSpinCount(&cs, 4000);

    HANDLE threads[THREAD_COUNT];
    for (int i = 0; i < THREAD_COUNT; ++i) {
        threads[i] = CreateThread(NULL, 0, IncrementCounter, NULL, 0, NULL);
    }

    WaitForMultipleObjects(THREAD_COUNT, threads, TRUE, INFINITE);

    DeleteCriticalSection(&cs);
    std::cout << "Counter: " << sharedCounter << std::endl; // Expected: 200000
    return 0;
}

Explanation: The CRITICAL_SECTION ensures atomic access to sharedCounter. Threads “enter” the critical section before modifying the variable and “leave” afterward.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *