473,396 Members | 1,886 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Synchronization methodology

Hi, I'm coming in from a despised Java background, and I'm having some
trouble wrapping my head around sharing an object between multiple
instances of a single class (in simpler terms, I would say imagine a
simple chat server that has to share a list of connected users to each
instance of a connected user).

Usually, I would have a synchronized list instantiated inside each
instance of a client class, which would do the trick, but since there's
no synchronization in Python, I'm stuck staring at little tests
involving a standalone non-threaded class instance that holds the list
of users, and each connected user being passed this instance to be
"synchronized".

Now, whilst this *works*, it just doesn't feel right, and I would
appreciate it if anyone has any more Pythonic expressions of this paradigm.

Note that I have looked at Twisted (and I use it for other stuff), but
I'm wanting to do things at a lower level (because I'm masochistic), and
I feel like all the fun has been sucked out of programming by basically
telling Twisted what I want and have it do it for me invisibly.

Thanks!
~Chris

Jan 3 '07 #1
6 2032
In <ma***************************************@python. org>, Chris Ashurst
wrote:
Hi, I'm coming in from a despised Java background, and I'm having some
trouble wrapping my head around sharing an object between multiple
instances of a single class (in simpler terms, I would say imagine a
simple chat server that has to share a list of connected users to each
instance of a connected user).

Usually, I would have a synchronized list instantiated inside each
instance of a client class, which would do the trick, but since there's
no synchronization in Python, I'm stuck staring at little tests
involving a standalone non-threaded class instance that holds the list
of users, and each connected user being passed this instance to be
"synchronized".
There's no ``synchronized`` keyword, but of course you can synchronize
methods. You have to attach an `threading.RLock` to the objects you want
to synchronize on and use its `aquire()` and `release()` methods in places
where you used ``synchronized (someObject) { ... }`` in Java.

synchronized foo() { /* code */ }

is the same as

foo() {
synchronized (this) { /* code */ }
}

in Java. And that's basically:

def foo(self):
self.lock.aquire()
# code
self.lock.release()

You may want to make sure the lock will be released in case of an
exception:

def foo(self):
self.lock.aquire()
try:
pass # code
finally:
self.lock.release()

Ciao,
Marc 'BlackJack' Rintsch
Jan 3 '07 #2
Chris Ashurst wrote:
Hi, I'm coming in from a despised Java background
Consider strongly the fact that Python supports multiple process
solutions well, so you're not stuck having to use multithreaded
solutions in every circumstance (but can still use them when necessary).

Jan 3 '07 #3
Chris Ashurst <ch***@telestatic.netwrites:
Hi, I'm coming in from a despised Java background, and I'm having some
trouble wrapping my head around sharing an object between multiple
instances of a single class (in simpler terms, I would say imagine a
simple chat server that has to share a list of connected users to each
instance of a connected user).
If you're doing this with threads, one common Pythonic style is
generally to have the threads communicate through queues (see docs for
the Queue module). This is sort of a cheap version of the CSP
(communicating sequential processes) approach. You might have a
service thread that takes care of those shared objects, reading
requests from a queue (untested):

# All client threads write their requests to this queue, and
# the service loop reads from it
service_queue = Queue()

# make one of these in each client thread
class Request(Queue.Queue):
def __call__(self, reply_queue, func, *args, **kwargs):
service_queue.put((self, func, args, kwargs))
return self.get()

def service_loop():
while True:
client, func, args, kwargs = service_queue.get()
client.put (func(*args, **kwargs))

Threading.Thread(target=service_loop).start()

Then in your connected user thread you could say:

# set up a reply queue for this user's thread
request = Request()
...

# add the user to the connected user list, with timestamp and remote IP
status = request(user_list.append, self, time(), remote_ip=whatever)

The last line would drop a request on the service queue to perform the
function call

user_list.append(time(), remote_ip=whatever)

The service queue thread would retrieve the request, call the
function, and pass the result back through the reply queue. The idea
is you'd handle all operations on user_list in the service thread, so
access is completely serialized using the queues. You can see that
you can easily construct any function call that then gets executed in
the other thread, without having to use a bunch of boilerplate at each
request. You have to be a bit careful to not use long-running
requests that could block other threads from getting their requests
serviced. Use additional threads if you need such requests.

You sometimes end up creating more threads than necessary this way but
you tend to not have many synchronization problems if you stick with
this style.
Jan 3 '07 #4
Paul Rubin <http://ph****@NOSPAM.invalidwrites:
# add the user to the connected user list, with timestamp and remote IP
status = request(user_list.append, self, time(), remote_ip=whatever)
Editing error, ignore the "self," arg up there. Of course there may be
other mistakes too, I didn't test any of that code ;-)
Jan 3 '07 #5
Marc 'BlackJack' Rintsch <bj****@gmx.netwrote:
You may want to make sure the lock will be released in case of an
exception:

def foo(self):
self.lock.aquire()
try:
pass # code
finally:
self.lock.release()
In Python 2.5 this can also be written more succintly using the with
statement so foo becomes:

from __future__ import with_statement
....

def foo(self):
with self.lock:
pass # insert your code here
or write a decorator.
Jan 3 '07 #6
Hi Chris,

Have you looked at the mutex module?

Jeremy

Jan 3 '07 #7

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

Similar topics

22
by: Ally | last post by:
Could someone give me an example of a modern development methodology? Just to see if I'm thinking along the right lines... P.S. Sorry for the cross posting but I couldn't find a newsgroup for...
4
by: scott | last post by:
hi all, Thx to any one that can offer me help, it will be much appreciated. iv got a multithreaded program and need to use thread synchronization. The synchronization does not have to...
0
by: Rod | last post by:
I orginally posted this to microsoft.public.sqlserver.ce but had not received any responses. I have a CF.NET application (C#) with a SqlCE database. We had originally planned to use SQL...
12
by: emma_middlebrook | last post by:
Hi Say you had N threads doing some jobs (not from a shared queue or anything like that, they each know how to do their own set of jobs in a self-contained way). How can you coordinate them so...
0
by: lbrtchx | last post by:
Say you need to serve the same Web content from a number of IP address, which you need to keep out there with high availability requirements ~ I think Web Services would be a good candidate for...
3
by: robtyketto | last post by:
Im a student and in preparation for a testIve been given the test questions (or thereabouts, they may be asked in different words or from another perspective). I've been told that they do not...
0
by: sundman.anders | last post by:
Hi all! I have a question about thread synchronization and c++ streams (iostreams, stringstreams, etc). When optimizing a program for a multicore processor I found that stringstream was causing...
3
by: CKKwan | last post by:
Dear All, Can synchronize a class, any function is called and the entire class is locked. Can synchronize a method What if I need to Lock a class only when specific method is call?
15
by: ingejg | last post by:
I am starting to study internet synchronization, and my head is still spinning since internet is not my forte, however my boss is breathing down my neck at the moment. Our company has only one...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
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...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.