0

我们正在尝试在 Python 中运行此代码,但是当函数 print_time 工作时,TestReactionTime 不执行(它甚至不打印)。对这两个函数的调用是相同的。

同样,独立地,当我们第一次释放球并尝试再次抓住它时,它会消失。

对于任何问题的任何帮助将不胜感激。

(我们使用的程序是 Vizard)

import viz
import math
import viztask
import vizinfo
import thread
import time

count = 0
boolTime = False

viz.setMultiSample(4)
viz.fov(20)
viz.go()

viz.phys.enable()
viz.phys.setGravity( [0, 0, 0] )
viz.window.setFullscreen()

viz.setOption('viz.model.apply_collada_scale',1)
ball = viz.add('ball.dae')
ball.setPosition([-0.1,1.5,4])
#ball.setScale([0.75,0.75,0.75])
ball.collideSphere()


viz.setOption('viz.model.apply_collada_scale',1)
path = viz.addChild('path.dae')
path.setPosition([-1,1.0,4])
path.collideMesh()

#collision
path.enable(viz.COLLIDE_NOTIFY)
def onCollide(e):
        global count 
        count = count+1
        print(count)

viz.callback( viz.COLLIDE_BEGIN_EVENT, onCollide )

#mouse
viz.mouse.setOverride(viz.ON) 
link = None 

**def TestReactionTime(threadName):**
    print 'boolTime: '
    print(boolTime)
    while boolTime:
        #Wait for next frame to be drawn to screen
        d = yield viztask.waitDraw()

        #Save display time
        displayTime = d.time

        #Wait for keyboard reaction
        d = yield viztask.waitMouseUp(viz.MOUSEBUTTON_LEFT)

        #Calculate reaction time
        reactionTime = d.time - displayTime
        print(reactionTime)

def print_time( threadName, delay):
   count = 0
   while count < 5:
      time.sleep(delay)
      count += 1
      print "%s: %s" % ( threadName, time.ctime(time.time()) )

def grabBall():
    global link
    global boolTime
    boolTime = True
    print("grab ")
    print(boolTime)
    try:
        #thread.start_new_thread( TestReactionTime,() )
        thread.start_new_thread( TestReactionTime, ("Thread-3", ) )
        thread.start_new_thread( print_time, ("Thread-1", 2, ) )
        print("execute thread")
    except:
        print "Error: unable to start thread"
    link = viz.grab( viz.Mouse, ball )


def releaseBall():
    global link,boolTime
    boolTime = False
    link.remove()
    link = None

vizact.onmousedown(viz.MOUSEBUTTON_LEFT,grabBall)
vizact.onmouseup(viz.MOUSEBUTTON_LEFT,releaseBall)
4

1 回答 1

1

一旦你创建了线程,你应该join让它们让主程序等待,直到每个线程完成执行。

thread模块不提供任何线程等待的规定。您应该使用推荐的Threading模块

thread.start_new_thread用_Thread()

    from threading import Thread

    #do something

    try:
       thread1 = Thread( target = TestReactionTime, args = ("Thread-3", ) )
       thread2 = Thread( target = print_time, args = ("Thread-1", 2, ) )

       thread1.start()
       thread2.start()

       thread1.join()
       thread2.join()

   #do the rest
于 2014-09-29T09:58:32.063 回答