Skip to main content
 首页 » 编程设计

Python 线程 'While' 不正常

2025年05月04日10小虾米

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

请您参考如下方法:

在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 视为局部变量并优化对其的访问。这样,local count 还没有在 while 循环中定义。

此外,去掉分号,Python 中不需要分号!