Wrapping Mutex Functionality

Hello,

I'm trying to wrap WINAPI's mutex functionality in a Mutex class.
I'm using a Mutex to throw an exception if more than one instance of the program is running.

However, no exception is thrown. Can someone help me out? Here's an example:

mutex.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#ifndef _MUTEX_H_
#define _MUTEX_H_
#include <windows.h>

class Mutex {
public:

	Mutex() : good(false) {}
	~Mutex();

	bool create();

	bool good;
	HANDLE handle;
	LPCWSTR name;

};

#endif 


mutex.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include "mutex.h"

Mutex::~Mutex() {
	if (good) {
		ReleaseMutex(handle);
		CloseHandle(handle);
	}
}

bool Mutex::create() {

	name = L"unique";
	handle = CreateMutex(nullptr, true, name);
	good = true;

	bool already_exists = (GetLastError() == ERROR_ALREADY_EXISTS);

	return already_exists;
}


main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <exception>
#include "mutex.h"

class ExceptionMutexInstance : public std::exception {
	virtual const char* what() const throw() {
		return "Another instance of the program is already running";
	}
};

int main(int argc, char* argv[]) {

	try {
		Mutex mutex;

		if (mutex.create()) {
			//already exists
			throw ExceptionMutexInstance();
		}
	}
	catch (std::exception& exception) {
		MessageBoxA(nullptr, exception.what(), "Error!", MB_OK | MB_ICONEXCLAMATION);
	}

	system("pause");
	return 0;
}


Thanks.
Last edited on
Just realized my simple mistake. The mutex object ceases to exist at the end of the try block. By the time the program pauses to allow me to open another instance of itself, the mutex has already called it's destructor. Totally overlooked that!
FWIW, there's a standard mutex class.
take a look at the MFC souce for CWinthread CMutex. they already wrapped it. Just copy what they did your just use what they already did
Last edited on
Thanks for the info guys!
Topic archived. No new replies allowed.