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

globalPython でグローバル変数を変更する場合は、次のキーワードを使用する必要があります。

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 では必要ありません。

于 2012-05-10T06:09:39.903 に答える
2

新しいローカル変数を作成するのではなく、グローバル カウントを使用するつもりであることを宣言する必要がglobal countあります。両方のスレッドの run メソッドに追加します。

于 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 に答える