Python线程'虽然'不行为

时间:2012-05-10 06:06:55

标签: python multithreading variables increment

好。所以我试图让2个线程运行并增加一个值,以便知道何时停止。我有点迷茫,因为我是Python的新手,一切看起来都对我..

import threading;
import socket;
import time;

count = 0;

class inp(threading.Thread):
    def run(self):
        while count < 11:
            time.sleep(0.5);
            print("Thread 1!");
            count += 1;

class recv_oup(threading.Thread):
    def run(self):
        while count < 31:
            time.sleep(0.5);
            print("Thread 2!");
            count += 1;

inp().start();
recv_oup().start();

错误很长......

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 551, in __bootstrap_inner
    self.run()
  File "core.py", line 9, in run
    while count < 11:
UnboundLocalError: local variable 'count' referenced before assignment

Exception in thread Thread-2:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 551, in __bootstrap_inner
    self.run()
  File "core.py", line 16, in run
    while count < 31:
UnboundLocalError: local variable 'count' referenced before assignment

我不知道发生了什么。正如我所说,对Python来说是新手,所以这对我来说都是胡言乱语。非常感谢任何帮助

3 个答案:

答案 0 :(得分:4)

在Python中,如果要修改全局变量,则需要使用global关键字:

class inp(threading.Thread):
    def run(self):
        global count
        while count < 11:
            time.sleep(0.5)
            print("Thread 1!")
            count += 1

否则,Python会将count视为局部变量并优化对它的访问。这样,在while循环中尚未定义 local count

另外,摆脱分号,Python中不需要它们!

答案 1 :(得分:2)

您必须声明您打算使用全局计数,而不是创建新的局部变量:将global count添加到两个线程中的run方法。

答案 2 :(得分:2)

由于您正在修改count的值,因此您需要将其声明为全局

class inp(threading.Thread):
    def run(self):
        global count
        while count < 11:
            time.sleep(0.5)
            print("Thread 1!")
            count += 1

class recv_oup(threading.Thread):
    def run(self):
        global count
        while count < 31:
            time.sleep(0.5)
            print("Thread 2!")
            count += 1