Basically I am trying to learn multithreading in C++. Platform: Windows XP. So far so good but I want to make sure I'm using mutex correctly. It compiles and runs as expected, but just wanted to make sure I use the CreateMutex() function in the correct place.

Thanks!

Here's my code (if it helps, I'm using Dev-C++):

#include 
#include 
#include 
#include 

using namespace std;

DWORD WINAPI myThreadFunc1(LPVOID param);
DWORD WINAPI myThreadFunc2(LPVOID param);
int readFile();

HANDLE hMutex;

int main(int argc, char *argv[])
{    
    hMutex = CreateMutex(NULL, false, "fileMutex");

    HANDLE myThread1 = CreateThread(NULL, 0, myThreadFunc1, NULL, 0, NULL);
    HANDLE myThread2 = CreateThread(NULL, 0, myThreadFunc2, NULL, 0, NULL);

    system("PAUSE");
    return EXIT_SUCCESS;
}

DWORD WINAPI myThreadFunc1(LPVOID param)
{
    readFile();
}

DWORD WINAPI myThreadFunc2(LPVOID param)
{
    readFile();
}

int readFile()
{   
    WaitForSingleObject(hMutex, INFINITE); 

    ifstream myReadFile;
    myReadFile.open("data.txt");
    char output[100];
    if(myReadFile.is_open()) 
    {
        while(myReadFile.getline(output, 100))
        {
            cout << output;
        }
        cout << endl;
    }
    myReadFile.close();

    ReleaseMutex(hMutex);

    return 0;

}

First of all, use CODE TAGS when you post code on this forum (not sure how you missed that with all of the information about it jumping in your eyes).

You got the general idea of a mutex right... but there are some things you should note.
First of all: You are not closing the handle to the mutex.
I am not 100% sure if Windows does this clean up for you, but nevertheless you should not rely on this. So close the handle when you don't need it anymore.

It is also a good idea to initialize the mutex HANDLE, eventhough creating the mutex is the first thing you application does... initializing variables should become a habit.

Lastly, a mutex is a kernel object, this means it can be shared between processes. You can make a mutex local, so accesible to your process only, by specifying NULL as name.
Since you are not sharing this mutex with another process this could be a good idea.
But that doesn't take away the fact that a mutex is a kernel object.
A slightly more effecient way of dealing with synchronization in Windows is by using CriticalSections (google it), these are usermode objects so slightly faster.


Edit: Also... don't use system( "PAUSE" )... read the stickies on these forum, they give you some nice tips that every c++ coder should know.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.