c - How to use critical section - Stack Overflow

PHOTO EMBED

Thu Apr 28 2022 07:46:39 GMT+0000 (UTC)

Saved by @wagm #c

#include <stdlib.h>
#include <stdio.h>
#include <windows.h>
#include <psapi.h>
#define SIZE_TAB 200

volatile char program[SIZE_TAB];
CRITICAL_SECTION CriticalSection;
DWORD WINAPI aa(void *v);
DWORD WINAPI bb(void *v);

int main(int argc, char *argv[])
{
InitializeCriticalSection(&CriticalSection);

HANDLE thread_a = CreateThread(NULL, 0, aa, 0, 0, 0);
HANDLE thread_b = CreateThread(NULL, 0, bb, 0, 0, 0);

while (1)
{
    for (int i = 0; i<SIZE_TAB; i++)
        printf("%c", program[i]);
    Sleep(1000);
    printf("\n\n");
}

DeleteCriticalSection(&CriticalSection);

CloseHandle(thread_a);
CloseHandle(thread_b);
return 0;
}


 DWORD WINAPI aa(void *v)
 {

    EnterCriticalSection(&CriticalSection);
    for (int i = 0; i < SIZE_TAB; i++)
    {
        program[i] = 'A';
        for (int j = 0; j<8000; j++);
    }
    LeaveCriticalSection(&CriticalSection);

   }

   DWORD WINAPI bb(void *v)
   {

    EnterCriticalSection(&CriticalSection);
    for (int i = 0; i<SIZE_TAB; i++)
    {
        program[i] = 'B';
        for (int j = 0; j<8000; j++);
    }
    LeaveCriticalSection(&CriticalSection);
   } 
content_copyCOPY

https://stackoverflow.com/questions/49722736/how-to-use-critical-section