buddy123
buddy123

Reputation: 6297

Accessing global variables from within a thread

I have python file with httpHandler class. I use it with ThreadingMixIn as follows:

from SocketServer import ThreadingMixIn
from 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 I initiate it as follows:

server = ThreadingHTTPServer(('localhost', PORT_NUMBER), httpHandler)
        print 'Started httpserver on port ' , PORT_NUMBER

So as I understand, the httpHandler class, once a connection is made, is already in a different thread. I want to keep track on my threads, some sort of statistics handling. However I cant access my variables. Also, I need to lock them, so that they'll represent real values, not something undefined correctly

Upvotes: 0

Views: 547

Answers (1)

sanyi
sanyi

Reputation: 6239

I would use a thread safe singleton for that.

Edit: johnthexiii suggested that I should post a simple example, so here it is. It's not exactly a singleton, but mimics one, class variables are global per application, so instead instantiating a singleton class we're working directly with the class, calling its class methods.

from threading import Lock


class ThreadSafeGlobalDataContainer:
    __container = {}
    __lock = Lock()

    @classmethod
    def set(cls, name, value):
        with cls.__lock:
            cls.__container[name] = value

    @classmethod
    def get(cls, name):
        with cls.__lock:
            return cls.__container[name]


#in some thread
ThreadSafeGlobalDataContainer.set('someName', 'someValue')

#somewhere else
print(ThreadSafeGlobalDataContainer.get('someName'))

Upvotes: 1

Related Questions