python - Accessing global variables from within a thread -
i have python file httphandler class. use threadingmixin follows:
from socketserver import threadingmixin basehttpserver import httpserver, basehttprequesthandler successful_attempts = 0 failed_attempts = 0 class httphandler(basehttprequesthandler): def do_post(self): ..... class threadinghttpserver(threadingmixin, httpserver): pass and later on initiate follows:
server = threadinghttpserver(('localhost', port_number), httphandler) print 'started httpserver on port ' , port_number so understand, httphandler class, once connection made, in different thread. want keep track on threads, sort of statistics handling. cant access variables. also, need lock them, they'll represent real values, not undefined correctly
i use thread safe singleton that.
edit: johnthexiii suggested should post simple example, here is. it's not singleton, mimics one, class variables global per application, instead instantiating singleton class we're working directly class, calling class methods.
from threading import lock class threadsafeglobaldatacontainer: __container = {} __lock = lock() @classmethod def set(cls, name, value): cls.__lock: cls.__container[name] = value @classmethod def get(cls, name): cls.__lock: return cls.__container[name] #in thread threadsafeglobaldatacontainer.set('somename', 'somevalue') #somewhere else print(threadsafeglobaldatacontainer.get('somename'))
Comments
Post a Comment