我是一个穿线的菜鸟。我正在尝试将一个函数作为一个重量级的线程来运行,而另一个函数则检查重量是否合理 - 如果重量不是,则关闭两个线程。这是在beagleboneblack上运行 - 但这可能不相关。为了简单起见,我在这里包含产生相同类型的不良行为的代码 - 但是简化了。
from time import sleep
import threading
import Queue
import random
exitFlagMass = 0
exitFlagWD = 0
mass = None
random.seed()
class massThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
#self.mass = None
def run(self):
global mass
print "Starting " + self.name
mass = massfunc(self.name)
print "Exiting " + self.name
def massfunc(threadName):
global exitFlagMass
global mass
while 1:
sleep(2.5)
print "exitFlagMass = "+str(exitFlagMass)
if exitFlagMass:
print "thread mass exiting"
thread.exit()
mass = random.random()*6
print str(mass)+" kg"
def wdfunc(threadName):
global exitFlagWD
global exitFlagMass
global mass
while 1:
#threadLock.acquire()
print "exitFlagWD = "+str(exitFlagWD)
if exitFlagWD:
print "thread wd exiting"
thread.exit()
if mass > 4.5:
print "greater than"+ str(4.5)+" kg"
exitFlagMass = 1
exitFlagWD = 1
#threadLock.release()
sleep(0.25)
class watchdogThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
self.masslimit = 4.5 #max kg weight
def run(self):
print "Starting " + self.name
wdfunc(self.name)
print "Exiting " + self.name
def main():
# Create new threads
weighthread = massThread(1, "weighthread-1", 1)
wdthread = watchdogThread(2, "wdthread-2", 1)
# Start new Threads
wdthread.start()
weighthread.start()
return 0
if __name__ == '__main__':
main()
这里的问题是wdthread永远不会开始。我希望有一个简单的解释。是因为我有两个线程类吗?如果是这样,我如何只使用一个线程类。
感谢您的帮助。
亲切的问候
马特
答案 0 :(得分:1)
我想你很早就回来了。
wdthread.join() # wait till the thread finishes
weighthread.join() # wait till the thread finishes
return 0
这将是你的问题。