2012-04-18 34 views
-3

我处于一种情况,我想根据正在线程中被调用的函数之一中更改的变量在循环中放入线程。这是我想要的。在Python中的线程中使用全局变量

error= 0 

while(error = 0) 
    run_thread = threading.Thread(target=self.run_test,args=(some arguments)) 

if (error = 0) 
    continue 
else: 
    break 

现在运行测试调用一个函数说A和A调用B和B调用C.

def A() 
     B() 
def B() 
    c() 

def c() 
    global error 
    error = 1 

这就是我想做的事情,但我不能工作了这一点。如果我尝试打印错误,我在代码中出现错误。

任何人都可以帮助我吗?

我是一个初学者,需要克服这个

+2

请格式化代码作为语法上有效的Python。 – jsbueno 2012-04-18 03:21:35

+0

应该是'(错误== 0)'? – 2012-04-18 04:08:39

+0

可能的重复[Python中的线程和全局变量](http://stackoverflow.com/questions/10202750/threads-and-global-variabes-in-python) – 2012-04-18 04:40:37

回答

0
error = False 

def A(): 
     B() 

def B(): 
    c() 

def c(): 
    global error 
    error = True 

def run_test(): 
    while not error: 
     A() 
    print "Error!" 

import threading 
run_thread = threading.Thread(target=run_test,args=()) 
run_thread.start() 

然而,它能够更好地继承线程,并重新实现的run(),并且还使用异常:

def A(): 
    raise ValueError("Bad Value") 

import threading 
class StoppableThread(threading.Thread): 
    def __init__(self, *args, **kwargs): 
     self.stop = False 

    def run(self): 
     while not self.stop: 
      A() #Will raise, which will stop the thread 'exceptionally' 

    def stop(self): #Call from main thread, thread will eventually check this value and exit 'cleanly' 
     self.stop = True 
+0

Thnaks的答复.Sorry,但我不完全清楚我的问题。那么我在while循环中运行两个线程,这使得这个解决方案对我无用我需要检查一个线程错误,但如果有一个,那么我需要重新运行这两个线程。所以我不能循环功能,但我需要循环线程。希望这一次我明确表示。我不能回答我的问题,因为形式规则,否则我可以重写代码描述 – 2012-04-18 04:21:28

+0

线程不能停止;如果你在while循环中产生线程,那么每次迭代都会产生一个线程。如果这就是你想要的,那就去做吧,但记得要调用线程的start()函数。请注意,除非实现等待条件,否则您将尽可能快地创建线程,而不会停止。也许尝试thread.join()? – 2012-04-18 04:35:26

+0

我不想停止线程。所有我想要的是在线程的末尾,检查是否有错误,如果有,然后只是重新运行这两个线程.....另外我在做thread.join()。有没有办法我可以做到这一点?/ ....我必须循环线程。所以给定的解决方案不适合我 – 2012-04-18 04:57:32