0

I can best explain this with example code first;

class reciever(threading.Thread,simple_server):
    def __init__(self,callback):
        threading.Thread.__init__(self)
        self.callback=callback

    def run(self):
        self.serve_forever(self.callback)

class sender(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.parameter=50

    def run(self):
        while True:
            #do some processing in general
            #....
            #send some udp messages derived from self.parameter
            send_message(self.parameter)

if __name__=='__main__':
    osc_send=sender()
    osc_send.start()

    def update_parameter(val):
        osc_send.parameter=val

    osc_recv=reciever(update_parameter)
    osc_recv.start()

the pieces I have left out are hopefully self explanatory from the code thats there..

My question is, is this a safe way to use a server running in a thread to update the attributes on a separate thread that could be reading the value at any time?

Matt Warren
  • 669
  • 8
  • 18
  • Your code is indented with only one space. Very unreadable; I would advice using two or four spaces. – Hidde Aug 15 '14 at 21:27
  • good point. just i tend to tab when writing code elswewhere and that doesnt work in a browser ... I'll edit it though :) – Matt Warren Aug 15 '14 at 21:28

1 Answers1

1

The way you're updating that parameter is actually thread-safe already, because of the Global Interpreter Lock (GIL). The GIL means that Python only allows one thread to execute byte-code at a time, so it is impossible for one thread to be reading from parameter at the same time another thread is writing to it. Reading from and setting an attribute are both single, atomic byte-code operations; one will always start and complete before the other can happen. You would only need to introduce synchronization primitives if you needed to do operations that are more than one byte-code operation from more than one threads (e.g. incrementing parameter from multiple threads).

Community
  • 1
  • 1
dano
  • 91,354
  • 19
  • 222
  • 219