I Want To Run And Kill A Thread On A Button Press
Solution 1:
Question: run and kill a thread on a button press
There is no such a thing called .kill(...
.
Start making your def send_file(...
a Thread object
which is waiting your commands.
Note: As it stands, your inner
while isready == 1:
will not stop by usingm.set_state('stop')
. It's mandatory to start theThread
object inside:
if __name__ == '__main__': m = MotorControl()
import threading, time
classMotorControl(threading.Thread):
def__init__(self):
super().__init__()
self.state = {'is_alive'}
self.start()
defset_state(self, state):
if state == 'stop':
state = 'idle'
self.state.add(state)
defterminate(self):
self.state = {}
# main function in a Thread objectdefrun(self):
# Here goes your initalisation# ...while'is_alive'in self.state:
if'start'in self.state:
isready = 1while isready == 1:
# Here goes your activity# Simulate activityprint('running')
time.sleep(2)
isready = 0
self.state = self.state - {'start'}
self.state.add('idle')
elif'idle'in self.state:
print('idle')
time.sleep(1)
if __name__ == '__main__':
m = MotorControl()
time.sleep(2)
m.set_state('start')
time.sleep(3)
m.set_state('stop')
time.sleep(3)
m.set_state('start')
time.sleep(4)
m.terminate()
print('EXIT __main__')
Your tk.Button
should look like:
tk.Button(text = "Run File", command = lambda:m.set_state('start'))
tk.Button(text = "Stop File", command = lambda:m.set_state('stop'))
tk.Button(text = "Terminate", command = m.terminate)
Solution 2:
The answer I have gone with is simple due to my simple understanding of threading and unique circumstances with which I am using the threading. Instead of terminating the thread in a way I was hoping, I added another conditional statement to the sending line of the send_file function.
while isready == 1:
for i inrange(len(pos1)):
if motorstop == False:
print("Step: " + str(i+1))
#data = struct.pack('!llllhhhhhhhh', pos1[i], pos2[i], pos3[i], pos4[i], speed1[i], speed2[i], speed3[i], speed[4], accel1[i], accel2[i], accel3[i], accel4[i])
data = struct.pack("!llhhhh", pos1[i], pos2[i], speed1[i], speed2[i], accel1[i], accel2[i])
ser.write(data)
else:
isready = 0break
and I have updated my stop() func to the following:
defstop():
try:
global motorstop
global t
motorstop = True
t.join()
except:
print("Error: thread wasn't killed")
I'm not exactly sure how it works but it is much simpler than what was mentioned by @stovefl.
With this code, since the function is mostly just sleeping, it can run but it won't send any new information and then will .join() after the next iteration.
Post a Comment for "I Want To Run And Kill A Thread On A Button Press"