1

好的。所以我试图让 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 新手,所以这对我来说都是胡言乱语。任何帮助是极大的赞赏

4

3 回答 3

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其视为局部变量并优化对它的访问。这样,本地 count尚未在 while 循环中定义。

另外,去掉分号,Python 不需要它们!

于 2012-05-10T06:09:39.903 回答
2

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

于 2012-05-10T06:10:01.553 回答
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
于 2012-05-10T06:10:29.183 回答