我目前正在使用Windows 8上的python v.2.7。
我的程序正在使用线程。我在创建它们时为这些线程提供了一个名称。第一个线程名为First-Thread
,第二个线程名为Second-Thread
。线程执行名为getData()
的方法,该方法执行以下操作:
compareValues()
compareValues
()中检索信息并将其添加到a
列表名为myList
compareValues()
执行以下操作:
我将这些线程的结果保存到名为myList
的列表中,然后最终打印此myList
。
问题:为什么我从未在Second-Thread
中看到myList
?我不明白这种行为。请尝试执行此代码以查看输出以了解我的问题。
代码:
import time
from random import randrange
import threading
myList = []
def getData(i):
print "Sleep for %d"%i
time.sleep(i)
data = compareValues()
for d in list(data):
myList.append(d)
def compareValues():
number = randrange(10)
if number >= 5:
yield "%s: Greater than or equal to 5: %d "%(t.name, number)
else:
yield "%s: Less than 5: %d "%(t.name, number)
threadList = []
wait = randrange(10)+1
t = threading.Thread(name = 'First-Thread', target = getData, args=(wait,))
threadList.append(t)
t.start()
wait = randrange(3)+1
t = threading.Thread(name = 'Second-Thread', target = getData, args=(wait,))
threadList.append(t)
t.start()
for t in threadList:
t.join()
print
print "The final list"
print myList
示例输出:
Sleep for 4Sleep for 1
The final list
['First-Thread: Greater than or equal to 5: 7 ', 'First-Thread: Greater than or equal to 5: 8 ']
感谢您的时间。
答案 0 :(得分:1)
def compareValues():
number = randrange(10)
if number >= 5:
yield "%s: Greater than or equal to 5: %d "%(t.name, number)
else:
yield "%s: Less than 5: %d "%(t.name, number)
在compareValues
的正文中,代码引用t.name
。当线程调用compareValues()
时t
根据LEGB rule查找并在全局范围中找到,引用第一个线程因为t.join()
正在等待第一个线程。 t.name
因此具有值First-Thread
。
要获取当前线程名称,请使用threading.current_thread().name
:
def compareValues():
number = randrange(10)
name = threading.current_thread().name
if number >= 5:
yield "%s: Greater than or equal to 5: %d "%(name, number)
else:
yield "%s: Less than 5: %d "%(name, number)
然后你会得到像
这样的输出Sleep for 4
Sleep for 2
The final list
['Second-Thread: Less than 5: 3 ', 'First-Thread: Greater than or equal to 5: 5 ']