473,657 Members | 2,497 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Cross process synchronization of shared resources

Hi,

I have two different things I'd like to discuss here. Both are about
cross-process synchronization of shared resources. The resources that
are shared are: (1) an object writing to a file and (2) a file. I
threat them as two different problems for various reasons.

The first problem involves the object writing to a file. The problem
might be best explained by thinking of a single log file that's
appended by different programs that interoperate. If we would do
nothing the file would be opened by the programs simultaneously and
written simultaneously, yielding incorrect log entries.

It is my understanding that types from the CLR are not shared and can
thus be used for locking the logging object. So in the logging object
we should be able to handle the condition as follows:

// locks the type of the logging object
lock (typeof(this))
{
// some code to demonstrate the idea...
StreamWriter sw = new StreamWriter(fi lename, true);
sw.WriteLine("{ 0}", logline);
sw.Close();
}

Since only this object should be responsible for writing the file,
this should work. If another object locks the file, the type won't be
locked, hence the StreamWriter will throw an exception. If another
program attempts to use the object and write an entry, it will run
into the lock.

I'd like to discuss if this is the/an appropriate way to handle this
problem and why.

The second point of discussion is in locking files between processes.
As far as I know the only way to do this properly is by checking if
the file is available on intervals and if so opening it. Since it is
important to open the file and thereby locking it instantly I believe
the way of doing that properly is wrapping the FileStream as follows:

// -- below is the wrapper class

public class LockingFileStre am : IDisposable {
private FileStream fs = null;

public LockingFileStre am(string filename) : base()
{
while (fs == null)
{
try
{
fs = File.Open(filen ame, FileMode.Open, FileAccess.Read Write,
FileShare.None) ;
}
catch (IOException e)
{
System.Threadin g.Thread.Sleep( 1000);
}
}

public FileStream Handle { get { return fs; } }

public void Dispose()
{
// make sure we release the lock here
if (fs != null)
{
fs.Close();
fs.Dispose();
fs = null;
}
}
}

// -- above is the wrapper; here follows a piece of code that uses it

void MyTest()
{
using (LockingFileStr eam lfs = new LockingFileStre am(myFilename))
{
// use lfs.Handle
}
}

// -------

However, this code polls the file to see if it's locked or not. I'd
rather use a monitor or mutex alike construction if that's in any way
possible.

Suggestions?

Cheers,

Stefan de Bruijn

Aug 14 '07 #1
7 8830
atlaste wrote:
It is my understanding that types from the CLR are not shared and can
thus be used for locking the logging object.
As the Type object is the same for all instances of an object, it's not
suitable for locking.
So in the logging object
we should be able to handle the condition as follows:

// locks the type of the logging object
lock (typeof(this))
You can't use the typeof keyword on an instance of a class, only on a type.

You should create a private object in the class, that you only use for
synchronising. The reason for this is that it prevents deadlocks, as
code outside the class can not lock on the same object.

Also, as that object is only used for synchronising and nothing else,
the risk is minimal that you should find some reason to expose it
outside the class. If you use some existing object in the class that is
used for something else, like for example filename, in the future you
might want to expose that object outside the class, not realising that
you create a potential for deadlocks.
{
// some code to demonstrate the idea...
StreamWriter sw = new StreamWriter(fi lename, true);
sw.WriteLine("{ 0}", logline);
sw.Close();
}

Since only this object should be responsible for writing the file,
this should work. If another object locks the file, the type won't be
locked, hence the StreamWriter will throw an exception. If another
program attempts to use the object and write an entry, it will run
into the lock.

--
Göran Andersson
_____
http://www.guffa.com
Aug 14 '07 #2
Dear Göran,

Thanks for the reaction. I think there is still some slight
miscommunicatio n, so I want to point out that this posting is only
about cross-process locking of shared resources (with multiple
programs using the same resource), while I think you reacted on

On Aug 14, 3:06 pm, Göran Andersson <gu...@guffa.co mwrote:
atlaste wrote:
It is my understanding that types from the CLR are not shared and can
thus be used for locking the logging object.

As the Type object is the same for all instances of an object, it's not
suitable for locking.
This was exactly the point. Since the type is the same for all
instances of the object, between different processes, it is very
suitable for locking between different processes. At the same time
it's very unsuitable for "normal" locking purposes.

Or do I misinterpret your comment?

.... reading it again I start to see your point. I'm locking the object
named "Type" rather than the type itself. Which means my proposed
(first) solution indeed will never work.
So in the logging object
we should be able to handle the condition as follows:
// locks the type of the logging object
lock (typeof(this))

You can't use the typeof keyword on an instance of a class, only on a type.
Sorry, I was writing the snippet in the news reader directly :-)
You should create a private object in the class, that you only use for
synchronising. The reason for this is that it prevents deadlocks, as
code outside the class can not lock on the same object.

Also, as that object is only used for synchronising and nothing else,
the risk is minimal that you should find some reason to expose it
outside the class. If you use some existing object in the class that is
used for something else, like for example filename, in the future you
might want to expose that object outside the class, not realising that
you create a potential for deadlocks.
That works fine if we're considering a single process / program that
runs multiple threads and uses the object for synchronization . In this
scenario I'm having multiple programs using the same shared DLL for
accessing the resource. As far as I know your solution doesn't work
there, does it?

Cheers,
Stefan de Bruijn.

Aug 15 '07 #3
Since the type is the same for all
instances of the object, between different processes,
As with any .NET object, Type instances do not cross process
boundaries, or even app-domains within a single process.

Equally (as already stated), in many eyes Type shouldn't be used for
locking anyway, since it is very public which can (if another
component is using the same trick) lead to unexpected deadlocks.

For cross-process (or app-domain) sync, either use a file, or
something like a named Mutex / Semaphore etc provided by the OS -
rather than the .NET Monitor ("lock") which is provided by the runtime
and hence is local to your app-domain.

Marc

Aug 15 '07 #4
On Aug 15, 11:01 am, Marc Gravell <marc.grav...@g mail.comwrote:
Since the type is the same for all
instances of the object, between different processes,

As with any .NET object, Type instances do not cross process
boundaries, or even app-domains within a single process.

Equally (as already stated), in many eyes Type shouldn't be used for
locking anyway, since it is very public which can (if another
component is using the same trick) lead to unexpected deadlocks.

For cross-process (or app-domain) sync, either use a file, or
something like a named Mutex / Semaphore etc provided by the OS -
rather than the .NET Monitor ("lock") which is provided by the runtime
and hence is local to your app-domain.
Thanks, that answers the first part of my question. I'll dive into the
named mutexes.

About the "file locking" approach I still wonder if there's a way to
lock on a file without a pulling approach (as I described in the first
posting).

Stefan.

Aug 15 '07 #5

On Aug 14, 2:17 pm, atlaste <atla...@gmail. comwrote:
this code polls the file to see if it's locked or not. I'd rather
use a monitor or mutex alike construction if that's in any way
possible.
I think it's easy to provoke a race condition in the inner lock if you
poll the file. Perhaps the FileSystemWatch er in cooperation with lock
files (.lock) would work, if you can make the operations sufficiently
atomic?

Aug 15 '07 #6

On Aug 15, 3:23 pm, UL-Tomten <tom...@gmail.c omwrote:
On Aug 14, 2:17 pm, atlaste <atla...@gmail. comwrote:
this code polls the file to see if it's locked or not. I'd rather
use a monitor or mutex alike construction if that's in any way
possible.

I think it's easy to provoke a race condition in the inner lock if you
poll the file. Perhaps the FileSystemWatch er in cooperation with lock
files (.lock) would work, if you can make the operations sufficiently
atomic?
And by "inner lock", for reasons unknown even to myself, I mean "file
lock".

Aug 15 '07 #7
atlaste wrote:
Dear Göran,

Thanks for the reaction. I think there is still some slight
miscommunicatio n, so I want to point out that this posting is only
about cross-process locking of shared resources (with multiple
programs using the same resource), while I think you reacted on

On Aug 14, 3:06 pm, Göran Andersson <gu...@guffa.co mwrote:
>atlaste wrote:
>>It is my understanding that types from the CLR are not shared and can
thus be used for locking the logging object.
As the Type object is the same for all instances of an object, it's not
suitable for locking.

This was exactly the point. Since the type is the same for all
instances of the object, between different processes, it is very
suitable for locking between different processes. At the same time
it's very unsuitable for "normal" locking purposes.

Or do I misinterpret your comment?

... reading it again I start to see your point. I'm locking the object
named "Type" rather than the type itself. Which means my proposed
(first) solution indeed will never work.
Actually, you are locking neither of those. A lock doesn't protect the
object in any way, the object is only used as an identifier for a mutex
to lock the code block. Another thread can not enter the same code block
at the same time.

However, as you have separate applications, a regular lock/mutex has no
effect at all, as they are local to the application. You have to use a
named mutex for that, as Marc suggested.
>>So in the logging object
we should be able to handle the condition as follows:
// locks the type of the logging object
lock (typeof(this))
You can't use the typeof keyword on an instance of a class, only on a type.

Sorry, I was writing the snippet in the news reader directly :-)
>You should create a private object in the class, that you only use for
synchronisin g. The reason for this is that it prevents deadlocks, as
code outside the class can not lock on the same object.

Also, as that object is only used for synchronising and nothing else,
the risk is minimal that you should find some reason to expose it
outside the class. If you use some existing object in the class that is
used for something else, like for example filename, in the future you
might want to expose that object outside the class, not realising that
you create a potential for deadlocks.

That works fine if we're considering a single process / program that
runs multiple threads and uses the object for synchronization . In this
scenario I'm having multiple programs using the same shared DLL for
accessing the resource. As far as I know your solution doesn't work
there, does it?
No, it doesn't.

(It does however work for every scenario where the lock keyword is used.)

--
Göran Andersson
_____
http://www.guffa.com
Aug 15 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
2428
by: Urs Vogel | last post by:
Hi For my application server, I had to overcome some limitations in older COM-database drivers, whers sessions per driver instance are limited. Instantiating the COM component several times does not help, since it still reports the same Process ID to the DB server, so the limit persists. When launching several external components (EXEs), each loading its own database driver, the limitation problem is solved. I built this using .Net...
35
5491
by: Alex Martelli | last post by:
Having fixed a memory leak (not the leak of a Python reference, some other stuff I wasn't properly freeing in certain cases) in a C-coded extension I maintain, I need a way to test that the leak is indeed fixed. Being in a hurry, I originally used a q&d hack...: if sys.platform in ('linux2', 'darwin'): def _memsize(): """ this function tries to return a measurement of how much memory this process is consuming, in some arbitrary unit...
18
6584
by: Dave Booker | last post by:
I have a Thread making a callback to a Form function that alters Form data. Of course, the debugger is telling me, "Cross-thread operation not valid: Control 'FormTest' accessed from a thread other than the thread it was created on." But I am locking before I touch the shared data, so do I actually need to worry about this, or is it just the debugger being oversimplistic? Specifically, I have:
5
12213
by: Tony Gravagno | last post by:
I have a class that instantiates two Timer objects that fire at different intervals. My class can be instantiated within a Windows Form or from a Windows Service. Actions performed by one of the event handlers may take longer than the interval for either of the timers, so it's possible for multiple events to fire "simultaneously" and for events to queue up. I'm attempting to get the timers to sync on some reference type object, or use...
3
1808
by: www.gerardvignes.com | last post by:
I do most JavaScript programming with objects and methods. I use tiny boot and shutdown scripts as hooks for the browser load and unload events. My JavaScripts interact with scripts running on the web server. I need to declare shared values (as constants) to assist communication between client and server. I declare these constants using global variables: var CONSTANT_NAME = 'whatever';
5
3595
by: nospam | last post by:
Hi all. I have encountered a "Cross-thread operation not valid" error in a test program I created and although I have came up with a solution I don't like the performance of the program. I hope perhaps some experts here can help me out. Here is what my program consists of: 1) A form containng several tabs, one of which contains a ListView
28
4932
by: Jon Davis | last post by:
We're looking at running a memory-intensive process for a web site as a Windows service in isolation of IIS because IIS refuses to consume all of the available physical RAM. Considering remoting to move data in and out of this process. Need something that's quick and dirty and easy to implement, but that's performant and secure at the same time. Any suggestions / tutorials? Would prefer not to go on the TCP/IP stack (socket) as it is not...
2
2397
by: Erick | last post by:
I've create a windows service which will start any windows application whose name it finds in an xml file i have pointed it to. However, I also want it to create .net objects from assemblies (dll's) I want these objects run in the background. I have used reflection to find the assembly and the object type. I want these objects to run separately to the windows service. Do i start these objects in a new thread or do they need to start...
0
1092
by: winkatl1213 | last post by:
I was wondering if anyone could help me with cross-compiling Python 2.5.1 to a MIPS target. The approach I'm using is based off the suggestion in the README file that comes with the python source distribution. I managed to get the configure script to run using the following command line: $ ../Python-2.5.1/configure --host=mips-linux --enable-shared
0
8392
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8823
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8503
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8603
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5632
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4151
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4301
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1944
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1604
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.