2014-09-29 54 views
0

我們試圖在Python中運行此代碼,但在函數print_time工作時,TestReactionTime不會執行(它甚至不會打印)。 對這兩個功能的調用是相同的。Python,線程函數不執行,對象消失

另外,獨立地,當我們第一次釋放球並嘗試再次抓住球時,它會消失。

任何有關任何問題的幫助將不勝感激。

(我們使用的程序是面頰)

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) 

回答

0

一旦你創建線程,你應該讓主程序等待,直到每個線程執行完畢join他們。

thread模塊不提供線程等待的任何規定。你應該使用recomended 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 
+0

謝謝,@ nu11p01n73R,我們改變了這一切。但它仍然不會進入TestReactionTime函數。它甚至不打印「布爾時間」。 – chopeds 2014-09-29 10:26:43