[IronPython] Converting C# to Python ... the lock() keyword?

Dino Viehland dinov at microsoft.com
Mon Jan 11 19:35:19 CET 2010


Correct - threading.Lock is a custom lock implementation (it's also non-reentrant)
so if you need to interoperate Monitor is the way to go.

> -----Original Message-----
> From: users-bounces at lists.ironpython.com [mailto:users-
> bounces at lists.ironpython.com] On Behalf Of Sandy Walsh
> Sent: Monday, January 11, 2010 10:31 AM
> To: Discussion of IronPython
> Subject: Re: [IronPython] Converting C# to Python ... the lock() keyword?
> 
> Thanks for the prompt answer Dino.
> 
> The lock is defined in a C# library and I have to access it ... I assume
> Monitor and threading.Lock() are different implementations (specifically, you
> can't mix and match)?
> 
> I can live with the Monitor for now I think.
> 
> Thanks again!
> -Sandy
> 
> 
> On 1/11/2010 2:23 PM, Dino Viehland wrote:
> > If you really want to use .NET monitors you can code it up as a try/finally:
> >
> > Monitor.Enter(m_object)
> > try:
> > 	if ...:
> > 		...
> > finally:
> > 	Monitor.Exit(m_object)
> >
> > If you'd like to do a slightly more Pythonic lock you could do:
> >
> > import threading
> >
> > x = threading.Lock()
> > with x:
> >      pass
> >
> > Or you could combine the two approaches:
> >
> > from System.Threading import Monitor
> > class ObjectLocker(object):
> >      def __init__(self, obj):
> >              self.obj = obj
> >      def __enter__(self):
> >              Monitor.Enter(self.obj)
> >      def __exit__(self, *args):
> >              Monitor.Exit(self.obj)
> >
> > with ObjectLocker(object()):
> >      pass
> >
> >
> >
> >
> >> -----Original Message-----
> >> From: users-bounces at lists.ironpython.com [mailto:users-
> >> bounces at lists.ironpython.com] On Behalf Of Sandy Walsh
> >> Sent: Monday, January 11, 2010 9:43 AM
> >> To: users at lists.ironpython.com
> >> Subject: [IronPython] Converting C# to Python ... the lock() keyword?
> >>
> >> Hi,
> >>
> >> I'm converting a C# program to IronPython and running into the C#
> >> lock() command ... what is the equivalent operation in IronPython?
> >>
> >> The C# is like:
> >>
> >>    lock(m_object)
> >>       if (...)
> >>       {
> >>        ...
> >>        }
> >>
> >> Thanks!
> >> -Sandy
> >>
> > _______________________________________________
> > Users mailing list
> > Users at lists.ironpython.com
> > http://lists.ironpython.com/listinfo.cgi/users-ironpython.com
> >
> >




More information about the Ironpython-users mailing list