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;
}