473,399 Members | 3,401 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,399 software developers and data experts.

Thread specific singleton

Hi,

I'm tring to implement a Singleton object that should be specific for
every thread who create it, not global.
I tried a solution that seems to work, but I have a very poor knowledge
of concurrent programming, so I'd like someone to help me find some
problems in my implementation.

Here is the code:

-------------------------------------------------------------

import thread

class ThreadLock(object):

locks = {}

def __new__(cls):
id = thread.get_ident()
try:
lock = cls.locks[id]
except KeyError:
lock = thread.allocate_lock()
cls.locks[id] = lock

return lock

@classmethod
def clear(cls, id=None):
""" Clear the lock associated with a given id.

If the id is None, thread.get_ident() is used.
"""

if id is None:
id = thread.get_ident()
try:
del cls.locks[id]
except KeyError:
pass

class ThreadedSingleton(object):

pool = {}

def __new__(cls, *args, **kw):
lock = ThreadLock()
lock.acquire()

id = thread.get_ident()
try:
obj = cls.pool[id]
except KeyError:
obj = object.__new__(cls, *args, **kw)
if hasattr(obj, '__init_singleton__'):
obj.__init_singleton__(*args, **kw)
cls.pool[id] = obj

lock.release()

return obj

def __del__(self):
id = thread.get_ident()
ThreadLock.clear(id)
try:
del cls.pool[id]
except KeyError:
pass

if __name__ == '__main__':

import time
import random

class Specific(ThreadedSingleton):

def __init_singleton__(self):
print "Init singleton"
self.a = None

def test(a):
s = Specific()
s.a = a
print "%d: %s" %(thread.get_ident(), Specific().a)
time.sleep(1)
print "%d: %s" %(thread.get_ident(), Specific().a)
time.sleep(random.randint(1, 5))
print "%d: %s" %(thread.get_ident(), Specific().a)
time.sleep(2)
print "%d: %s" %(thread.get_ident(), Specific().a)

for x in range(4):
thread.start_new_thread(test, (x, ))

time.sleep(10)

-------------------------------------------------------------

using the thread module should be fine even if threads are created
trought the threading module, right ?

Thanks,
Gabriele
Jun 9 '06 #1
2 2959
In article <44***********************@reader1.news.tin.it>,
Gabriele Farina <g.******@html.it> wrote:

I'm tring to implement a Singleton object that should be specific for
every thread who create it, not global.
I tried a solution that seems to work, but I have a very poor knowledge
of concurrent programming, so I'd like someone to help me find some
problems in my implementation.


Try using threading.local(), but you'll need 2.4 or later.
--
Aahz (aa**@pythoncraft.com) <*> http://www.pythoncraft.com/

"I saw `cout' being shifted "Hello world" times to the left and stopped
right there." --Steve Gonedes
Jun 12 '06 #2

Gabriele Farina wrote:
Hi,

I'm tring to implement a Singleton object that should be specific for
every thread who create it, not global.
I tried a solution that seems to work, but I have a very poor knowledge
of concurrent programming, so I'd like someone to help me find some
problems in my implementation.

Here is the code:

-------------------------------------------------------------

import thread

class ThreadLock(object):

locks = {}

def __new__(cls):
id = thread.get_ident()
try:
lock = cls.locks[id]
except KeyError:
lock = thread.allocate_lock()
cls.locks[id] = lock

return lock

@classmethod
def clear(cls, id=None):
""" Clear the lock associated with a given id.

If the id is None, thread.get_ident() is used.
"""

if id is None:
id = thread.get_ident()
try:
del cls.locks[id]
except KeyError:
pass

class ThreadedSingleton(object):

pool = {}

def __new__(cls, *args, **kw):
lock = ThreadLock()
lock.acquire()

id = thread.get_ident()
try:
obj = cls.pool[id]
except KeyError:
obj = object.__new__(cls, *args, **kw)
if hasattr(obj, '__init_singleton__'):
obj.__init_singleton__(*args, **kw)
cls.pool[id] = obj

lock.release()

return obj

def __del__(self):
id = thread.get_ident()
ThreadLock.clear(id)
try:
del cls.pool[id]
except KeyError:
pass

if __name__ == '__main__':

import time
import random

class Specific(ThreadedSingleton):

def __init_singleton__(self):
print "Init singleton"
self.a = None

def test(a):
s = Specific()
s.a = a
print "%d: %s" %(thread.get_ident(), Specific().a)
time.sleep(1)
print "%d: %s" %(thread.get_ident(), Specific().a)
time.sleep(random.randint(1, 5))
print "%d: %s" %(thread.get_ident(), Specific().a)
time.sleep(2)
print "%d: %s" %(thread.get_ident(), Specific().a)

for x in range(4):
thread.start_new_thread(test, (x, ))

time.sleep(10)

-------------------------------------------------------------

using the thread module should be fine even if threads are created
trought the threading module, right ?

Thanks,
Gabriele


import thread

class Singleton:
pass

singletons = {}

def get_singleton():
ident = thread.get_ident()
try:
singleton = singletons[ident]
except KeyError:
singleton = Singleton()
singletons[ident] = singleton
return singleton

Jun 12 '06 #3

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

Similar topics

8
by: Robert Zurer | last post by:
I have a server application that makes a MarshalByReferenceObject available via remoting. It's lifetime is set to never expire and it is implemented as a Singleton. Are calls to this object...
15
by: Mountain Bikn' Guy | last post by:
Is the second version shown below better? I couldn't locate enough info about in order to tell. 1.. My commonly used singleton pattern implementation looks like this (it was inspired by Eric...
5
by: CannonFodder | last post by:
hi all, im new to c# and i think i may have coded myself into a bit of a mess. basically i am writing a windows service which audits all the pcs on a network using WMI on a regular basis. The...
11
by: PJ | last post by:
I'd like to create a subsystem in my asp.net application that is responsible for emails that need to be send out based upon certain events so that the main request/response threads aren't...
1
by: Diffident | last post by:
Guys, I have been cracking my head over this concept in .NET framework. I have read many posts on this topic but not clear about this and hence I am posting it again. If you have designed...
11
by: Eric | last post by:
I have a VB.net dll project with a class that is a singleton. I've been using this in winform apps without any problems. I would like to use this same dll in a web form project but my singleton...
7
by: intrader | last post by:
I have the following small classes: //----------------code--------------- using System; using System.Collections.Generic; using System.Text; namespace ValidatorsLibrary { public class...
4
by: Smithers | last post by:
Does the FileSystemWatcher class, when enabled, spawn a new thread for itself? I googled and somehow just found people having random problems with the FileSystemWatcher class and the MSDN docs....
1
by: =?Utf-8?B?QU1lcmNlcg==?= | last post by:
Sorry this is so long winded, but here goes. Following the model of http://msdn2.microsoft.com/en-us/library/system.runtime.remoting.channels.ipc.ipcchannel.aspx I made a remote object using the...
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
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
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
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...

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.