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

Home Posts Topics Members FAQ

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(obje ct):

locks = {}

def __new__(cls):
id = thread.get_iden t()
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_iden t() is used.
"""

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

class ThreadedSinglet on(object):

pool = {}

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

id = thread.get_iden t()
try:
obj = cls.pool[id]
except KeyError:
obj = object.__new__( cls, *args, **kw)
if hasattr(obj, '__init_singlet on__'):
obj.__init_sing leton__(*args, **kw)
cls.pool[id] = obj

lock.release()

return obj

def __del__(self):
id = thread.get_iden t()
ThreadLock.clea r(id)
try:
del cls.pool[id]
except KeyError:
pass

if __name__ == '__main__':

import time
import random

class Specific(Thread edSingleton):

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

def test(a):
s = Specific()
s.a = a
print "%d: %s" %(thread.get_id ent(), Specific().a)
time.sleep(1)
print "%d: %s" %(thread.get_id ent(), Specific().a)
time.sleep(rand om.randint(1, 5))
print "%d: %s" %(thread.get_id ent(), Specific().a)
time.sleep(2)
print "%d: %s" %(thread.get_id ent(), Specific().a)

for x in range(4):
thread.start_ne w_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 2979
In article <44************ ***********@rea der1.news.tin.i t>,
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**@pythoncra ft.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(obje ct):

locks = {}

def __new__(cls):
id = thread.get_iden t()
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_iden t() is used.
"""

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

class ThreadedSinglet on(object):

pool = {}

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

id = thread.get_iden t()
try:
obj = cls.pool[id]
except KeyError:
obj = object.__new__( cls, *args, **kw)
if hasattr(obj, '__init_singlet on__'):
obj.__init_sing leton__(*args, **kw)
cls.pool[id] = obj

lock.release()

return obj

def __del__(self):
id = thread.get_iden t()
ThreadLock.clea r(id)
try:
del cls.pool[id]
except KeyError:
pass

if __name__ == '__main__':

import time
import random

class Specific(Thread edSingleton):

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

def test(a):
s = Specific()
s.a = a
print "%d: %s" %(thread.get_id ent(), Specific().a)
time.sleep(1)
print "%d: %s" %(thread.get_id ent(), Specific().a)
time.sleep(rand om.randint(1, 5))
print "%d: %s" %(thread.get_id ent(), Specific().a)
time.sleep(2)
print "%d: %s" %(thread.get_id ent(), Specific().a)

for x in range(4):
thread.start_ne w_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_iden t()
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
3966
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 inherently thread safe? If 1000 threads all call the same method of this object at once, do I have to add anything to my code to assure that there are no problems? Excuse me if this is really obvious. I am somewhat new to remoting and totally new...
15
5398
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 Gunnerson's book): private static volatile MyClass singleton = null; private static object sync = new object();//for static lock public static MyClass Instance {
5
4122
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 main processes are performed in a Windows Service which scans Active Directory and for each computer found it adds a process to the threadpool. the process creates a new instance of a class which does the WMI querying, this creates an XML file...
11
1634
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 responsible for the communication with the smtp server, etc. I don't want to create a seperate thread for every instance in which a notification must be sent...I'd rather record the necessary information to the db or web cache and let the subsystem be...
1
1235
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 your class based on singleton pattern where ONLY ONE instance of class exists for the WHOLE APPLICATION DOMAIN....how can the public methods in that class be thread-safe? I have read thru posts where they say that singleton class methods are...
11
4907
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 will cause problems because some sessions may need different values in the singleton. I want to change my singleton to store a private hashtable with different instances. I guess this is more like a factory pattern now but that doesn't matter ...
7
1996
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 ValidatorBase {
4
1698
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. MSDN online didn't clarify (at least not that I found). My situation is that I have a Windows Forms app. The application class hosts a singleton instance of another class. That other class communicates with the hosting app primarily via events...
1
1707
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 IpcChannel Class (vs 2005, vb, fw 2.0). Everyting works fine. The object is registered with WellKnownObjectMode.Singleton The remote object appears at the bottom of this posting. The code is deliberately obtuse to expose an issue about when...
0
8319
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8837
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...
0
8739
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8612
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
7347
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5638
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
4171
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...
2
1969
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1732
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.