DonationCoder.com forum
 
Read-only archive. This is a static copy of the DonationCoder.com forum. Reading and searching work as before; logging in, posting and private messages do not.
Archive of 2026-10-21 · About this archive · Main site

Author Topic: Mutex Problem  (Read 12,338 times)

Codebyte

  • "Premature Optimization is the root of all evil."
  • Supporting Member
  • Joined in 2007
  • **
  • Posts: 160
    • Participated in NANY Challenge Once
    • Coding Snacks
    • Plugin Coding Medal
Mutex Problem
« on: July 15, 2008, 06:15 PM »
Im using RAD Studio... This is the code:

Code
//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop
//---------------------------------------------------------------------------
USEFORM("Unit1.cpp", Form1);
//---------------------------------------------------------------------------
WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
	HANDLE mutex;
	try
	{
		const char mutexname[] = "SingleInstanceProgram";
		mutex = OpenMutex(0, false, mutexname);
		if(mutex == NULL)
		{
			mutex = CreateMutex(NULL, true, mutexname);
		}
		else
		{
			ShowMessage("Application is already running.");
			return 0;
        }
		Application->Initialize();
		SetApplicationMainFormOnTaskBar(Application, true);
		Application->CreateForm(__classid(TForm1), &Form1);
		Application->Run();
	}
	catch (Exception &exception)
	{
		Application->ShowException(&exception);
	}
	catch (...)
	{
		try
		{
			throw Exception("");
		}
		catch (Exception &exception)
		{
			Application->ShowException(&exception);
		}
	}
	ReleaseMutex(mutex);
	return 0;
}
//---------------------------------------------------------------------------

Somehow, every time i launched the compiled executable it seems to just recreate the mutex as if it was never created in the first place... Any Ideas?
CodeByter.com - http://www.codebyter.com

Jibz

  • Cold Warrior
  • Developer
  • Joined in 2005
  • ***
  • Posts: 1,187
    • Programming School - Stage 1 Medal
    • Coding Snacks
    • Participated in NANY Challenge Four Times
Re: Mutex Problem
« Reply #1 on: July 15, 2008, 06:55 PM »
The default permissions probably allow another process to open the mutex. I have used something along the lines of the following in the past:

Code
// attempt to create mutex
hMutex = CreateMutex(NULL, FALSE, szMutexName);

// get error state
dwVal = GetLastError();

// check if creating the mutex succeeded
if (dwVal != ERROR_SUCCESS)
{
    // if we got a handle to an already existing object, close it
    if (dwVal == ERROR_ALREADY_EXISTS) CloseHandle(hMutex);

    // exit
    return 0;
}

...

CloseHandle(hMutex);
"A problem, properly stated, is a problem on it's way to being solved" -Buckminster Fuller
"Multithreading is just one damn thing after, before, or simultaneous with another" -Andrei Alexandrescu

Codebyte

  • "Premature Optimization is the root of all evil."
  • Supporting Member
  • Joined in 2007
  • **
  • Posts: 160
    • Participated in NANY Challenge Once
    • Coding Snacks
    • Plugin Coding Medal
Re: Mutex Problem
« Reply #2 on: July 15, 2008, 07:30 PM »
works, like a charm! you rock :) ty
CodeByter.com - http://www.codebyter.com

Codebyte

  • "Premature Optimization is the root of all evil."
  • Supporting Member
  • Joined in 2007
  • **
  • Posts: 160
    • Participated in NANY Challenge Once
    • Coding Snacks
    • Plugin Coding Medal
Re: Mutex Problem
« Reply #3 on: July 15, 2008, 07:47 PM »
one more thing, kind of irrelevant depending on how you look at it... Is there a windows API call that I could use to close a process that is currently open?
CodeByter.com - http://www.codebyter.com

Jibz

  • Cold Warrior
  • Developer
  • Joined in 2005
  • ***
  • Posts: 1,187
    • Programming School - Stage 1 Medal
    • Coding Snacks
    • Participated in NANY Challenge Four Times
Re: Mutex Problem
« Reply #4 on: July 15, 2008, 08:09 PM »
Depends on what you mean by closing a process.

If you mean you have opened a handle to a process, and you want to close that handle, then CloseHandle.

If you mean you are a thread in the process you wish to close, then ExitProcess.

If you mean terminating another process that you are not directly involved in, then TerminateProcess (which is a bit harsh, and you might be better off adding some method of closing the process if you are the one coding it).
"A problem, properly stated, is a problem on it's way to being solved" -Buckminster Fuller
"Multithreading is just one damn thing after, before, or simultaneous with another" -Andrei Alexandrescu

f0dder

  • [Well, THAT escalated quickly!]
  • Charter Honorary Member
  • Joined in 2005
  • ***
  • Posts: 9,153
    • Participated in NANY Challenge Once
Re: Mutex Problem
« Reply #5 on: July 15, 2008, 10:52 PM »
And in case Jibz should ever change his signature, I'll post the second line from it here, because it's scaringly true, and somewhat related to this thread (a mutex can be used as a threading synchronization primitive, after all):
Quote
"Multithreading is just one damn thing after, before, or simultaneous with another" -Andrei Alexandrescu
- carpe noctem

Deozaan

  • Charter Member
  • Joined in 2006
  • ***
  • Posts: 9,827
    • Participated in NANY Challenge Eight Times
    • Cody Award
Re: Mutex Problem
« Reply #6 on: July 17, 2008, 07:24 AM »
And I'll quote the first line, because a lot of the times when I'm "stuck" on a programming issue I can't figure out, I end up thinking of the solution in the process of describing the problem to someone I'm asking for help.

Quote
"A problem, properly stated, is a problem on it's way to being solved" -Buckminster Fuller

Codebyte

  • "Premature Optimization is the root of all evil."
  • Supporting Member
  • Joined in 2007
  • **
  • Posts: 160
    • Participated in NANY Challenge Once
    • Coding Snacks
    • Plugin Coding Medal
Re: Mutex Problem
« Reply #7 on: July 18, 2008, 03:23 AM »
How do I free these Threads on Terminate?

Code
//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
HANDLE Thread;
//---------------------------------------------------------------------------
DWORD WINAPI Thread1(LPVOID Param);
DWORD WINAPI Thread2(LPVOID Param);
//---------------------------------------------------------------------------
DWORD WINAPI Thread2(LPVOID Param)
{
	//code here
	ShowMessage("test2");
	//terminate Thread
	TerminateThread(Thread, false);
	return 0;
}
//---------------------------------------------------------------------------
DWORD WINAPI Thread1(LPVOID Param)
{
	//code here
	ShowMessage("test");
	//terminatethread
	TerminateThread(Thread, false);
	return 0;
}
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
	: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
	//initialize the thread to CheckRegistry
	DWORD Id;
	Thread = CreateThread(0, 0, CheckRegistry, Form1->Handle, CREATE_SUSPENDED, &Id);
	ResumeThread(Thread);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button2Click(TObject *Sender)
{
	//initialize the thread to CheckRegistry
	DWORD Id;
	Thread = CreateThread(0, 0, RefreshStore, Form1->Handle, CREATE_SUSPENDED, &Id);
	ResumeThread(Thread);
}
//---------------------------------------------------------------------------
CodeByter.com - http://www.codebyter.com

Jibz

  • Cold Warrior
  • Developer
  • Joined in 2005
  • ***
  • Posts: 1,187
    • Programming School - Stage 1 Medal
    • Coding Snacks
    • Participated in NANY Challenge Four Times
Re: Mutex Problem
« Reply #8 on: July 18, 2008, 07:13 AM »
If you do not need access to the thread while it is doing it's job, you can free the handle you get from CreateThread right away with CloseHandle.

If you do need access to it, it probably means you are going to be waiting for some kind of result from it, which you can do using the WaitForSingleObject/WaitForMultipleObjects functions.

By the way, it appears there is a potential problem in your code; if the user presses Button1 a thread is created and the handle is stored in a global variable, if the user presses Button2 while the thread is running, this global variable is overwritten with the handle of the second thread.
"A problem, properly stated, is a problem on it's way to being solved" -Buckminster Fuller
"Multithreading is just one damn thing after, before, or simultaneous with another" -Andrei Alexandrescu

Codebyte

  • "Premature Optimization is the root of all evil."
  • Supporting Member
  • Joined in 2007
  • **
  • Posts: 160
    • Participated in NANY Challenge Once
    • Coding Snacks
    • Plugin Coding Medal
Re: Mutex Problem
« Reply #9 on: July 19, 2008, 01:59 AM »
Here is my problem... no matter what I do I seem to be getting these errors that cause my program to bug out on close... I get Error 1400: Invalid Window Handle... but I have been able to identify that this occurs only when some threads are created... I cant seem to find the problem so I think that there is something I'm missing when it comes to this whole thread thing... Basically, the extent of my program is using a thread to take care of ftp work in the background so the ftp component wont lock up the program... it seems to work great except that I tend to get bugs here and there... idk though... I got Error 1400: Invalid Window Handle on RAD Studio startup screen earlier tonight.. 1st time ever... so it might not be me... any ideas? i can send you the source in private if u need... i've just smacked into the wall and cant get passed it
CodeByter.com - http://www.codebyter.com

Jibz

  • Cold Warrior
  • Developer
  • Joined in 2005
  • ***
  • Posts: 1,187
    • Programming School - Stage 1 Medal
    • Coding Snacks
    • Participated in NANY Challenge Four Times
Re: Mutex Problem
« Reply #10 on: July 19, 2008, 07:40 AM »
I don't have RAD studio myself, so I wouldn't be able to compile it I'm afraid.

I am sure there must be some way to compile with debug information turned on, which should let you pinpoint the exact place in your code where the error occurs. Then you will have to look through the code and figure out why and how to fix it.

It does sound a bit troublesome if the IDE gives you the error before you even start running your code though, may be a bug in that.
"A problem, properly stated, is a problem on it's way to being solved" -Buckminster Fuller
"Multithreading is just one damn thing after, before, or simultaneous with another" -Andrei Alexandrescu

Codebyte

  • "Premature Optimization is the root of all evil."
  • Supporting Member
  • Joined in 2007
  • **
  • Posts: 160
    • Participated in NANY Challenge Once
    • Coding Snacks
    • Plugin Coding Medal
Re: Mutex Problem
« Reply #11 on: July 19, 2008, 04:02 PM »
Fixed it :)
http://www.codebyter.com/codebyter-software-updater/
CodeByter.com - http://www.codebyter.com
« Last Edit: July 20, 2008, 10:56 PM by Codebyte »

Original address: https://www.donationcoder.com/forum/index.php?topic=14075.0