Writing into a file using two threads

  c++, operating-system, windows

I’m trying to put together a program that uses threads and file functions , this is the code

#include <windows.h>
#include <iostream>
#include <fstream>
#include <mutex>
using namespace std;

//global handle for semaphore and mutex and file
HANDLE hsemaphore;
HANDLE hmutex;
int i = 1;
fstream FileX;

//thread function
DWORD WINAPI MySyncFun(LPVOID lpParam)
{
    while (i <= 20) {
        FileX.open("FileX.txt", ios::in);
        if (!FileX) {
            cout << "file not created!" << endl;
        }
        else {
            WaitForSingleObject(hsemaphore, INFINITE);
            WaitForSingleObject(hmutex, INFINITE); //mutex lock

            FileX << "count-" << i++ << endl;
            FileX.close();

            ReleaseMutex(hmutex); //mutex unlock
            ReleaseSemaphore(hsemaphore, 1, 0);
        }
    }
    return 0;
}
int main()
{
    //local variable
    HANDLE hthread1;
    HANDLE hthread2;

    //step 1 create semaphore
    hsemaphore = CreateSemaphore(
        NULL,
        2,
        2,
        NULL);
    if (NULL == hsemaphore) {
        cout << "semaphore creation failed & error No- " << GetLastError() << endl;
    }
    cout << "semaphore creation success" << endl;

    //step 2 mutex creation
    hmutex = CreateMutex(
        NULL,
        FALSE,
        NULL);
    if (NULL == hmutex) {
        cout << "mutex creation failed & error no- " << GetLastError() << endl;
    }
    cout << "mutex creation success" << endl;

    //step 3 create 2 threads
    hthread1 = CreateThread(
        NULL,
        0,
        &MySyncFun,
        NULL,
        0,
        0);

    hthread2 = CreateThread(
        NULL,
        0,
        &MySyncFun,
        NULL,
        0,
        0);

    //step 4 wait for single object for all threads
    WaitForSingleObject(hthread1, INFINITE);
    WaitForSingleObject(hthread2, INFINITE);

    //close handle for threads
    CloseHandle(hthread1);
    CloseHandle(hthread2);

    //close handle for the mutex
    CloseHandle(hmutex);

    //close handle for the semaphore
    CloseHandle(hsemaphore);

    //Opening the file to show its content
    FileX.open("FileX.txt", ios::out);
    char ch;
    if (!FileX) {
        cout << "file not created!" << endl;
    }
    else {
        while (1) {
            FileX >> ch;
            if (FileX.eof())
                break;
            cout << ch;
        }
    }

    system("PAUSE");
    return 0;
}

The comments show the steps I took , the output gives me that the file is not created , it prints the "file not created " in a loop from 1 to 20 , but it also gives that the semaphore and mutex both created successfully.

Why is the file not created? Should I not define it globally?

The point of this code is to have two threads writing stuff in a text file.

Source: Windows Questions

LEAVE A COMMENT