jeffpkamp
jeffpkamp

Reputation: 2866

python sharing variables between active threads

I have a program which runs a camera for a set number of exposures and a set length of exposures through a serial port. The program talks to a server which gives error values, if the error values are within an acceptable range, then the exposure starts and a countdown clock runs until the exposure ends. The following variables are used to make this happen.

T="Length of exposure in seconds" N="Number of exposures"

then a while loop runs the program using the following

    def countdown(n):
       for i in range(int(n)):
        c = int(n) - int(i)
        print c ,'seconds left','\r',
        time.sleep(1)  

While x < T loop: 
        countdown(n)

I would like to run a thread which is constantly probing the error number from the server, and if the error number grows to large, it changes to the value of i to equal n.

def errortest():
                    test=struct.pack("B",10)
                    s.send(test)
                    data = s.recv(BUFFER_SIZE)
                    if ord(data) < (75) and ord(data) > 0:
                        print ord(data)
                        time.sleep(5)
                    else:
                        print ("error! Stopping exposure")
                        i=n

My problem is that the variables aren't being shared between the functions. I had some success with setting "i" and "n" as global variables, but this has caused other problems as well, depending on the order in which I invoke or write the different functions. I've also tried return i=n, but n is not shared. It is especially a problem as both threads are running concurrently and not sharing variables. This is why I cannot get queue to work because it pauses the for loop at each instance of q.get().

Is there a better way than using global variables to share variable values between functions running as concurrent threads?

Upvotes: 0

Views: 360

Answers (1)

Dietrich
Dietrich

Reputation: 5551

You might want to try sharing your variables within a class. You'll find many tutorials if you google for them. If you want to distribute your tasks into different programs, xmlrpc is a simple possibility.

Upvotes: 1

Related Questions