Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manage concurrent Input/Output access to a XML file from multiple instances of an EXE, using Delphi.

Tags:

xml

mutex

delphi

I have a command line tool, written in Delphi, which job is to insert a node in a XML file and then immediately exit. I need to make it possible several instances of the tool to be executed simultaneously and insert nodes to one and the same XML.

To achieve this purpose I have introduced a simple file "mutex" - the tool creates one temp file before writing to the XML and then deletes the temp file after finished witing. So if another instance is executed, it checks for the presence of this temp file and waits until it is deleted. Then it creates again the temp file, writes to the XML and deletes the temp file.

The problem is that this works fine only when 2-3 instances try to write to the XML file simultaneously. When there are more instances - some of them just wait forever and never append the node into the XML.

Is there a better way to make it work with large number of instances running and writing to the XML at the same time?

like image 662
m_pGladiator Avatar asked Sep 19 '08 12:09

m_pGladiator


2 Answers

A named semaphore or mutex can do this for you on a single machine. Use e.g. TMutex from SyncObjs, and use one of the constructors which takes a name argument. If you use the same name in all the applications, they will be synchronizing over the same kernel mutex. Use TMutex.Acquire to access, and TMutex.Release when you're done, protected in a try/finally block.

Use the TMutex.Create overload which has an InitialOwner argument, but specify False for this (unless you want to acquire the mutex straight away, of course). This overload calls CreateMutex behind the scenes. Look in the source to SyncObjs and the documentation for CreateMutex for extra details.

like image 70
Barry Kelly Avatar answered Nov 03 '22 00:11

Barry Kelly


1 - Set up a file which records pending changes (it will work like a queue)

2 - Write a simple app to watch that file, and apply the changes to the XML file

3 - Modify the current command-line tool to append their change requests to the "Pending changes" file

Now only one app has to touch the final XML file.

like image 35
JosephStyons Avatar answered Nov 03 '22 00:11

JosephStyons