0

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

2
  • A very low-level idea would be creating a global list and store variables in it. But you have to watch out not to write the same list at the same time with two different threads (as you said a lock needs to be provided) but if you just got 2 threads (main and some working one) you could just read with main and just write with the working one without trouble (and the need of a lock) - just a comment becaus there might be a better way Commented Aug 16, 2013 at 11:29
  • 1
    @Martin, from what I've seen Queues seem to be the defacto way for sharing information between threads in python. Commented Aug 16, 2013 at 12:04

1 Answer 1

1

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')) 
Sign up to request clarification or add additional context in comments.

2 Comments

Could you post a simple example of that?
@johnthexiii here it is

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.