3

我是一个线程菜鸟。我正在尝试将一个函数作为一个衡量某物的线程运行,另一个检查权重是否合理——如果权重不正确,则关闭两个线程。这是在 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 永远不会启动。我希望有一个简单的解释。是因为我有两个线程类吗?如果是这样,我该如何只用一个线程类来做到这一点。

谢谢你的帮助。

亲切的问候

马特

4

1 回答 1

1

我想你很早就回来了。

wdthread.join() # wait till the thread finishes
weighthread.join() # wait till the thread finishes

return 0

这将是你的问题。

于 2013-11-11T09:15:15.213 回答