【问题标题】:Python Threads 'While' not BehavingPython线程'虽然'没有表现
【发布时间】:2012-05-10 06:06:54
【问题描述】:

好的。所以我试图让 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 中,您通常不使用分号结束语句。
  • 欢迎使用 python - 它是一种了不起的语言!作为提示,您不需要使用 ';' 来终止语句-- 语句以换行符结束,所以只需按回车键!
  • -1:在 Stack Overflow 上,我们希望用户在提出新问题之前进行一些研究。在您的情况下,搜索您得到的错误 (UnboundLocalError) 应该可以让您立即找到解决方案!
  • 我做到了。我什么也没找到。这就是我来这里的原因。显然不是每个人都能找到他们正在寻找的东西,当一个帖子接近 3 个月时。对不起。

标签: python multithreading variables increment


【解决方案1】:

在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 中是不需要的!

【讨论】:

  • 哦,不知道。非常感谢。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    由于要修改 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多