Python Exchange Class Instance Among Threads

I have a class that loads all the resources into memory needed for my application (mostly images).

Then, multiple threads must access these resources through this class. I do not want each instance to reload all resources, so I decided to use the Singleton template. I did it like this:

class DataContainer(object):
    _instance = None
    _lock = threading.Lock()
    _initialised = True

    def __new__(cls, *args, **kwargs):
        with cls._lock:
            if not cls._instance:
                cls._initialised = False
                cls._instance = object.__new__(cls, *args, **kwargs)
        return cls._instance

    def __init__(self, map_name = None):

        # instance has already been created
        if self._initialised:
            return

        self._initialised = True

        # load images

This works great if I don't use multiple threads. But when using multiple threads, each thread has a different instance. Thus, using 4 threads, each of them creates a new instance. I want all threads to use the same instance of this class, so resources are only loaded once into memory.

I also tried to do this in the same module where the class is defined, but outside the class definition:

def getDataContainer():
    global dataContainer
    return dataContainer

dataContainer = DataContainer()

- .

python, , plz ,

+3
1

@Will, " " , , .

( . multiprocessing.Manager, , .)

import threading, time


class SharedObj(object):
    image = 'beer.jpg'


class DoWork(threading.Thread):
    def __init__(self, shared, *args, **kwargs):
        super(DoWork,self).__init__(*args, **kwargs)
        self.shared = shared

    def run(self):
        print threading.current_thread(), 'start'
        time.sleep(1)
        print 'shared', self.shared.image, id(self.shared)
        print threading.current_thread(), 'done'


myshared = SharedObj()
threads = [ DoWork(shared=myshared, name='a'), 
            DoWork(shared=myshared, name='b')
]
for t in threads:
    t.start()
for t in threads:
    t.join()
print 'DONE'

:

<DoWork(a, started 140381090318080)> start
<DoWork(b, started 140381006067456)> start
shared beer.jpg shared140381110335440
 <DoWork(b, started 140381006067456)> done
beer.jpg 140381110335440
<DoWork(a, started 140381090318080)> done
DONE

, , SharedObj, , 440.

+1
source

All Articles