Page 1 of 1

Threading

Posted: Mon Aug 03, 2020 4:09 am
by mogo4414
Hello,

I'm trying to control multiple stepper motors/limit switches with a single raspberry pi. I am writing a program to do this. My thought was to have multiple threads which call the same function and each motor would move based on the functions called and corresponding limit switch position (NC/NO etc..).

My concern is:

If two separate threads were created which called the same function, that had a variable; would each thread iteration change the variable value for each other or would the variable changes be contained to each thread?

For example:

*Threads "A" and "B" created/called*

If thread A called a function "C()" and changes its variable "c" to 1 and thread B also called function "C()" and also changes variable "c", but this time to 2. Would thread A, on its next iteration, now read a "c" value of 2?

(I was trying to test this myself but ending up running into some results that were a bit perplexing. So just hoping to get a second opinion.)

Thanks in advance for the help!

Re: Threading

Posted: Mon Aug 03, 2020 12:34 pm
by ghp
now read a "c" value of 2 ? : yes or no, it depends on the scope of the variable
If c is a "global" variable, then the answer is yes.

Code: Select all

import threading
import time

c = 0

def c_function():
    global c
    c += 1
    print(c)
    
def run_A():
    time.sleep(1.0)
    c_function()
    time.sleep(1.0)
    
def run_B():
    time.sleep(1.5)
    c_function()
    time.sleep(0.5)
    
threading.Thread(target=run_A).start()
threading.Thread(target=run_B).start()
If c is a 'thread local' variable, then no.

Code: Select all

import threading
import time
    
class AB:
    def __init__(self, name):
        self.name = name
        
        self.c = 0
        threading.Thread(target=self.run_AB).start()  
        
    def c_function(self):
        self.c += 1
        print("{name:s} {value:d}".format(name= self.name, value = self.c))
        
    def run_AB(self):
        time.sleep(1.0)
        self.c_function()
        time.sleep(1.0) 
    
a = AB("a")
b = AB("b")
 

Re: Threading

Posted: Mon Aug 03, 2020 12:45 pm
by rpiMike
I don’t see why you would need threads. Just one rapid loop testing limit switches and controlling stepper motors.

Re: Threading

Posted: Mon Aug 03, 2020 4:52 pm
by mogo4414
ghp,

Thank you for taking the time do detail that all out!

And yes that is very helpful. In my test code I have some local and global variables, so it would make sense that I was getting mixed results. I'm going to redesign the code a little to remove the global variables, so hopefully that will keep each thread separate!

----

rpiMike,

I forgot to mention that I am using a Tkinter interface and the motor control function uses time delays. So without threading, the interface would be very stalled and difficult to use without it. (I'm not familiar with using a "rapid' testing loop, in general though.)